Dictionaries
Table of Contents
1. Dictionaries
Dictionaries are collections of key-value pairs: they map keys to values. There are two restrictions on dictionary keys:
- A key cannot be a list or a dictionary (or any mutable type)
- Two keys cannot be equal: there is only one value for one key
You can build a dictionary with a literal like so:
numerals = {'I': 1, 'V': 5, 'X': 10}
You can also lookup the value for a particular key, similar to indexing syntax:
val = numerals['X'] # 10
However, we cannot use indices on dictionaries: you must use a key, as dictionaries are not sequences. We can, however, iterate on the dictionary by turning it into a sequence like so:
keys = list(numerals) # ['I', 'V', 'X']
vals = numerals.values() # dict_values([1, 5, 10])
We can also find the length of a dictionary:
length = len(numerals) # 3
1.1. Dictionary Comprehensions
You can build a dictionary using a dictionary comprehension, whose syntax is as follows:
{<key>: <value> for <name> in <iterable> if <condition>}
Just like list comprehensions, the filter <condition> is optional.
1.2. Dictionary Iteration
In a dictionary, its keys, values, and items are all iterable values and can produce iterators using iter(). Note that in modern versions of Python (3.6+) the order of items in a dictionary is the order in which they were added, but in older versions items appeared in an arbitrary order. For example:
d = {'one': 1, 'two': 2, 'three': 3}
d['zero'] = 0
k = iter(d.keys()) # Iterator over keys of dictionary
v = iter(d.values()) # Iterator over values of dictionary
i = iter(d.items()) # Iterator over itmes of dictionary: returns tuple (key, value)
Additionally, changing the size of the dictionary will invalidate the iterator.