Learn R Programming

Dict (version 0.6)

dict: Creates a new dictionary

Description

Creates a new dictionary based on the specified key/value pairs.

Usage

dict(...)
default_dict(..., .default = NULL)
strict_dict(...)
immutable_dict(...)

Arguments

...
key and value pairs. All arguments must be named.
default
a default value to be returned when a non-existing key is accessed.

Value

a new dictionary object.

Details

These functions are used to build a new dictionary object filled with the key = value pairs passed as arguments. Typical dictionary objects are created using dict. If a key is not specified, an implicit key is assumed.

Dictionary objects are equivalent to named lists, but have a few advantages over them.

Firstly, all values contained in dictionary objects are always associated with a unique character key. This means that values can only be accessed using their respective keys, and not using integer indices, which is more consistent with the intended usage. Empty or repeated keys are not allowed.

Secondly, keys are never partially matched; for instance, my_dict$k will not match my_dict$key but will instead return NULL.

Dictionary object can store NULLs as values; assigning NULL to a key will not delete that key from the dictionary, but set the value associated with that key to NULL. To remove a key, use the omit function.

Finally, printing of dicts is more compact that printing named lists.

Dictionaries are implemented using named lists, so they can be passed to functions that expect lists.

default_dict creates a dictionary with default values. When the user accesses a non-existing key, the default value will be returned instead of NULL.

strict_dict creates a dictionary such that when the user accesses a non-existing key, an exception will be raised instead of returning NULL.

immutable_dict creates a dictionary that cannot be modified (see immutable).

Examples

Run this code
person <- dict(name = "Joan", last_name = "Smith", age = 30)

color <- 'blue'
pattern <- 'vertical'
fill <- dict(color, pattern)

salaries <- default_dict(employee_A = 100, employee_B = 50,
                         employee_C = 75, default = 60)

enumeration <- strict_dict(YES = 1, NO = 0)

Run the code above in your browser using DataLab