
26
|
Python Pocket Reference
Dictionaries
Dictionaries are mutable (i.e., changeable) tables of object
references, accessed by key, not position. They are unor-
dered collections, implemented internally as dynamically
expandable hash tables.
Literals and creation
Dictionaries are written as comma-separated series of key:
value
pairs inside curly braces. Assigning to new keys gener-
ates new entries. Any immutable object can be a key (e.g.,
string, number, tuple), and class instances can be keys if they
inherit hashing protocol methods. Tuple keys support com-
pound values (e.g.,
adict[(M,D,Y)], with parentheses
optional).
{}
An empty dictionary.
{'spam': 2, 'eggs': 3}
A two-item dictionary: keys 'spam' and 'eggs'.
adict = { 'info': { 42: 1, type("): 2 }, 'spam': [] }
Nested dictionaries: adict['info'][42] fetches 1.
adict = dict(zip('abc', [1, 2, 3]))
Creates a dictionary by passing the key/value tuples list
to the type constructor.
adict = dict(name='Bob', age=42, job=('mgr', 'dev'))
Creates a dictionary by passing keyword arguments to
the type constructor.
Operations
Operations comprise all mapping operations (see Table 5,
earlier in this book), plus the following dictionary-specific
methods.