dictionary

Lookup table that maps keys to values.

Category: Language Fundamentals > Data Types

Syntax

d = dictionary()

Creates an empty dictionary whose types are set by the first entry.

d = dictionary(keys, values)

Creates a dictionary from arrays of keys and values.

d = dictionary(k1, v1, k2, v2, ...)

Creates it from key and value pairs.

Description

Read with d(key) and write with d(key) = value; writing an existing key replaces the value, and writing a new key adds an entry. Reading a missing key is an error unless you use lookup with a fallback. Other operations: isKey(d, k), keys(d), values(d), numEntries(d), remove(d, k) and entries(d).

Assigning [] to a key, as in d("a") = [], removes it.

Input arguments

keys
Array of unique keys: numbers or strings.
values
Array with one value per key, or a cell array.

Output arguments

d
A dictionary. Unlike containers.Map, it is a value object, so a copy is independent of the original.

Example

Create, query and update

d = dictionary("a", 1, "b", 2);
d("c") = 3;
d("a")
isKey(d, ["a" "q"])
numEntries(d)
d
Output
ans = 1
ans = 1×2 logical array

   1   0
ans = 3
d = 
  dictionary (string --> double) with 3 entries:

    "a" --> 1
    "b" --> 2
    "c" --> 3

Notes

remove raises an error when the key is absent, even if a FallbackValue is passed.

See also

configureDictionary containers.Map entries isKey struct