Learn R Programming

container (version 0.3.0)

dictS3: Dict constructors

Description

The dict resembles Python's dict type, and is implemented as a specialized associative (or mapping) container thus sharing all container methods with some of them being overriden to account for the associative key-value pair semantic.

Usage

dict(x = list())

as.dict(x)

is.dict(x)

getval(x, ...)

keys(x)

popitem(x)

setval(x, ...)

sortkey(x, ...)

Arguments

x

initial elements passed to constructor or object of class Dict passed to member methods.

...

further arguments

S3 methods for class <code>Dict</code>

add(dic, key, value)

If key not yet in dic, insert value at key, otherwise signal an error.

discard(dic, key)

If key in dic, remove it.

has(dic, key)

TRUE if key in dic else FALSE.

remove(dic, key)

If key in dic, remove it, otherwise raise an error.

getval(dic)

If key in dic, return value, else throw key-error.

keys(dic)

Return a character vector of all keys.

peek(dic, key, default=NULL)

Return the value for key if key is in the dic, else default.

pop(dic, key)

If key in dic, return a copy of its value and discard it afterwards.

popitem(dic)

Remove and return an arbitrary (key, value) pair from the dictionary. popitem() is useful to destructively iterate over a dic, as often used in set algorithms.

setval(dic, key, value, add=FALSE)

Like add but overwrites value if key is already in the dic. If key not in dic, an error is thrown unless add was set to TRUE.

sortkey(dic, decr=FALSE)

Sort values in dictionary according to keys.

update(dic, other=dict())

Adds element(s) of other to the dictionary if the key(s) are not in the dictionary and updates all keys with the new value(s) otherwise.

See Also

container, Dict, +.Dict, [<-.Dict, [[<-.Dict, [[.Dict, [.Dict

Examples

Run this code
# NOT RUN {
ages <- dict(c(Peter=24, Lisa=23, Bob=32))
has(ages, "Peter")   # TRUE
ages["Lisa"]         # 23
ages["Mike"]         # NULL
ages["Mike"] <- 18
ages["Mike"]         # 18
keys(ages)
print(ages)

# }
# NOT RUN {
ages["Peter"] <- 24 + 1     # key 'Peter' already in Dict
dict(c(Peter=24, Peter=20)) # Error: duplicated keys
# }

Run the code above in your browser using DataLab