Learn R Programming

container (version 0.3.0)

Dict: A Dict class

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

Arguments

Format

An object of class R6ClassGenerator of length 24.

Inherited methods

Inherits all methods from Container but overrides the internal initialize function and the following member functions:

add(key, value)

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

discard(key)

If key in Dict, remove it.

has(key)

TRUE if key in Dict else FALSE.

remove(key)

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

R6 constructor

Dict$new(x=list())

Dict methods

get(key)

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

keys()

Return a character vector of all keys.

peek(key, default=NULL)

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

pop(key)

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

popitem()

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

set(key, value, add=FALSE)

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

sort(decr=FALSE)

Sort values in dictionary according to keys.

update(other=Dict$new())

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

See Also

Container

Examples

Run this code
# NOT RUN {
ages <- Dict$new(c(Peter=24, Lisa=23, Bob=32))
ages$has("Peter")   # TRUE
ages$peek("Lisa")   # 23
ages$peek("Mike")   # NULL
ages$add("Mike", 18)
ages$peek("Mike")   # 18
ages$keys()
print(ages)

# }
# NOT RUN {
Dict$new(list(Peter=20))$add("Peter", 22)         # key already in Dict
Dict$new(c(Peter=24, Lisa=23, Bob=32, Peter=20))  # Error: duplicated keys
# }

Run the code above in your browser using DataLab