Dictionaries in python are known in other languages by other names, including "associative arrays" and "mappings". The latter being perhaps the more explanatory term. Dictionaries are basically a set of mappings from a key to a value. Keys can be of any non-mutable type, and values can be of any type including other dictionaries, lists, or tuples. Dictionaries specify a set of key:value pairs, such that when the dictionary is subscripted using a key it contains, the value associated with that pair is returned.
Dictionaries are formed using curly braces ({ }
), and
providing a comma separated list of key:value pairs between the open
and close braces.
Python 2.4.3 (#1, Oct 2 2006, 21:50:13) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = { ... 0: "This is the value for key 0", ... 1: "This is the value for key 1", ... "3": "See how keys can also be strings", ... (4, 5): "Or even tuples", ... "and for fun": 7 ... } >>>
Here we have a new dictionary, which we have assigned to a variable
'a'. The dictionary contains five key:value pairs, each specified using
the format <key> : <value>
within a comma
separated list within curly braces. Note how keys can be of multiple
different types within the same dictionary. Key order is not
guaranteed by python. Similarly values can be of any type, and
types can be mixed within one dictionary. Also note the existence of
the empty dictionary ...
>>> b = {} >>>
Presumably, the first thing we would want to be able to do after
forming a dictionary is to manipulate the key:value pairs. We would
want to be able to extract individual pairs by their key name, which we
do by using the subscription operator
<dictionary>[<expression>]
>>> a[0] 'This is the value for key 0' >>> a["3"] 'See how keys can also be strings' >>> a[4,5] 'Or even tuples' >>>
In a similar way to lists we can change the contents of a
dictionary, meaning dictionaries are mutable.
Specifically, we can change the value of a certain key using the
assignment statement <dictionary>[<expression>] =
<expression>
.
>>> a["3"] = "Told you keys could also be strings" >>> a["3"] 'Told you keys could also be strings' >>>
Similarly, a simple assignment statement can add a new key:value pair to a dictionary, as long as the key doesn't already exist in the dictionary. If the key does already exist, it's value is simply changed as in the assignment statement above.
>>> a["new"] = "a new pair has been added" >>> a {0: 'This is the value for key 0', 1: 'This is the value for key 1', '3': 'Told you keys could also be strings', 'new': 'a new pair has been added', (4, 5): 'Or even tuples'} >>>
It is important to realise, that this implicit replacement of the values of already extant keys ensures that keys are unique. Also, note that attempting to access a key that doesn't exist causes an error...
>>> a[3] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 3 >>>
Which means that before we can add to the value of a particular key
using an assignment such as
a["n"] = a["n"] + 1
we
must first ensure the key exists to add to. The same is of course true
of any operator applied to a key's value. The reason for this is that
assignments evaluate the expression on the right of the equals before
assigning it to the variable on the left, meaning the value of a["n"]
would be looked up before it has been put into the dictionary, causing
an error.
Entire dictionaries can be compared using the standard comparison operators. If 'a' and 'b' are both dictionaries
a == b
yields Equivalence. True only if both
'a'and 'b' contain exactly the same set of key:value pairs.a < b
, a <= b
yield Less
Thana > b
, a >= b
yield Greater
Thana is b
is True only if 'a' and 'b' are synonyms
for the same dictionary.We can loop over the keys of a dictionary, using a for statement.
>>> for k in a: ... print k ... 0 1 3 new (4, 5) >>>
Or perhaps more usefully, we can loop over the keys, and use them as indexes into the dictionary.
>>> for k in a: ... print k, ":", a[k] ... 0 : This is the value for key 0 1 : This is the value for key 1 3 : Told you keys could also be strings new : a new pair has been added (4, 5) : Or even tuples >>>
Finally, we can extract various structures from a dictionary in the form of lists.
<dictionary>.values()
returns a list
containing all values in the dictionary. The order of these
values is not guaranteed.
>>> a.values() ['This is the value for key 0', 'This is the value for key 1', 'Told you keys could also be strings', 'a new pair has been added', 'Or even tuples'] >>>
<dictionary>.keys()
returns a list
containing all keys in the dictionary. The order of these keys
is not guaranteed.
>>> a.keys() [0, 1, '3', 'new', (4, 5)] >>>
<dictionary>.items()
returns a list
containing tuples of all key:value pairs in the dictionary,
where key is the first element of the tuple, and value the
second. The order of these pairs is not guaranteed.
>>> a.items() [(0, 'This is the value for key 0'), (1, 'This is the value for key 1'), ('3', 'Told you keys could also be strings'), ('new', 'a new pair has been added'), ((4, 5), 'Or even tuples')] >>>
Given the code:
d = { "fruits": ["apples", "oranges", "pears", "mangoes"], "vegetables": ["tomatoes", "lettuce", "spinach", "green peppers"], "meat": ["chicken", "fish", "beef", "ostrich"], "dairy": ["yogurt", "milk", "cheese", "ice-cream"] }
d["meat"]
?d["dairy"][2]
?