More About Dictionaries¶
Dictionaries¶
Associative arrays …
Stores pairs of key and value
Keys are unique
⟶ no two keys with the same value can exist in the same dictionary object
Fast lookup
Internally realized as a hash table
Keys are not sorted
No deterministic iteration possible
Dictionary Access¶
|
Insert (or overwrite) |
|
returns value of |
|
returns value of |
|
returns value of |
|
remove entry for |
|
iterable over keys |
|
iterable over values |
|
iterable over data as |
|
number of entries (as with all non-scalar types) |
|
return value if there, else insert |
|
merge dictionary |
|
does |
|
does |
Examples: Simple Access¶
>>> d = {} # empty
>>> d = {'one': 1, 'two': 2}
>>> d['one']
1
>>> d.get('one')
1
>>> d.get('three')
None
>>> d['three']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'three'
Examples: Shortcuts¶
Shortcuts for what would otherwise be too much code …
>>> d.get('three', 3)
3
>>> d.get('three')
None
|
>>> d.setdefault('three', 3)
3
>>> d['three']
3
|
Dictionary Iteration (1)¶
Iteration is a fundamental concept in Python
… even more so in Python 3
⟶ compatibility alert!
>>> d.keys()
dict_keys(['three', 'one', 'two'])
>>> list(d.keys())
['three', 'one', 'two']
>>> d.keys()
['three', 'two', 'one']
>>> d.iterkeys()
<dictionary-keyiterator object at 0x7ff2e8753418>
Dictionary Iteration (2)¶
>>> list(d.values())
[3, 1, 2]
>>> list(d.items())
[('three', 3), ('one', 1), ('two', 2)]
Wait:
d.item()
lets me iterate over tuples …Why shouldn’t I use tuple unpacking then?
for key, value in d.items():
...
Building Dictionaries¶
>>> d = {}
>>> d = {1: 'one', 2: 'two'}
>>> d = dict()
>>> d = dict({1: 'one', 2: 'two'})
>>> d = dict([('one', 1), ('two', 2), ('three', 3)])