dict: Python-style Dictionaries in R

Description Usage Arguments Details Warning Examples

View source: R/dict.R

Description

Dictionaries, i.e., hashed key-value pairs, are implemented in R using environments as a backend.

Usage

1
dict(..., `_size` = 29L)

Arguments

...

Named arguments used in constructing the dictionary.

'_size'

The number of 'buckets' used. This is the maximum of 29L and the number of named arguments passed to ....

Details

Dictionaries are just hashed R environments with emptyenv() as a parent.

Warning

Dictionaries have reference semantics, so modifying a dictionary within a function will modify the dictionary passed in, not a copy! Use the copy function to duplicate a dict.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
## Reference semantics -- be careful!
x <- dict()
y <- x
x[["a"]] <- 100
print(y[["a"]])

## Use copy to be explicit
y <- copy(x)
x[["b"]] <- 200
try(y[["b"]], silent = TRUE)

## Named lookup can be much faster in a dictionary
x <- as.list(1:1E5)
names(x) <- paste0("Element_", 1:1E5)
dict <- as.dict(x)
if (require(microbenchmark)) {
  microbenchmark(
    x[["Element_1"]],
    dict[["Element_1"]],
    x[["Element_1000"]],
    dict[["Element_1000"]],
    x[["Element_100000"]],
    dict[["Element_100000"]]
  )
}

kevinushey/Kmisc documentation built on May 20, 2019, 9:08 a.m.