Chapter 10 Dictionaries

10.1 Dicts - A Mutable Mapping Type

All of the compound data types that have been studied in detail so far — strings, lists, and tuples — are sequential collections. This means that the items in the collection are ordered from left to right and they use integers as indices to access the values they contain.

Dictionaries are a different kind of collection. They are Python’s built-in mapping type. A map is an unordered, associative collection. The association, or mapping, is from a key, which can be any immutable type, to a value, which can be any Python data object.

As an example, to create a dictionary to translate English words into Spanish. For this dictionary, the keys are strings and the values will also be strings.

One way to create a dictionary is to start with the empty dictionary and add key-value pairs. The empty dictionary is denoted {}

Activity: CodeLens 1 (ten1Example1)

The first assignment creates an empty dictionary named d. The other assignments add new key-value pairs to the dictionary. The left hand side gives the dictionary and the key being associated. The right hand side gives the value being associated with that key. The current value of the dictionary can be shown using print. The key-value pairs of the dictionary are separated by commas. Each pair contains a key and a value separated by a colon.

The order of the pairs may not be what you expected. Python uses complex algorithms, designed for very fast access, to determine where the key-value pairs are stored in a dictionary. Because of this, the ordering is unpredictable.

Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output.

Activity: CodeLens 2 (ten1Example2)

It doesn’t matter what order the pairs are. The values in a dictionary are accessed with keys, not with indices, so there is no need to care about ordering.

Here is how a key is used to look up the corresponding value.

Activity: CodeLens 3 (ten1Example3)

The key 'two' yields the value 'dos'.

When two duplicated keys are defined in a dict literal, the latter overrides the former.

>>> d = {'a': 1, 'b': 2, 'a': 3}
>>> d
{'a': 3, 'b': 2}

In the example above, d contains two identical keys, which are mapped into the integers 1 and 3, respectively. Python discards the key value pair (‘a’, 1), keeping only (‘a’, 3) for the key ‘a’. Python uses the == operator to decide whether two keys are identical. As a result, two numerical values can be identical even if their types are different.

>>> d = {1: 'a', 2: 'b', 1.0: 'c'}
>>> d
{1: 'c', 2: 'b'}

In the example above, the keys 1 and 1.0 are treated as identical because the expression 1 == 1.0 is True. As immutable objects, floating point numbers can be used as keys to dicts. However, due to rounding off errors, Python’s representation of floating point numbers can be imprecise. These can also be conflit with integer keys as shown above. As a result, it is recommended to avoid the use of floating point numbers as keys when possible.

Dict operators similar to tuples and lists, the == and != operators can be used to find the equality between dict objects. Dicts are unordered collections, the order in which items are specified or added to a dict object does not affect the value of the dict object.

>>> d1 = {1:'a', 2: 'b', 3: 'c'}
>>> d2 = {3:'c', 1: 'a', 2: 'b'}
>>> d3 = {}
>>> d1 == d2
True
>>> d1 != d3
True

The lookup operation is the most commonly used operation for dict objects. The syntax is formally identical to that of the getitem operation for tuples and lists, which specify the index of an item by a pair of square brackets. The only difference is that for a dict object, a key is used in the place of the index for tuples and lists.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> d[1]
'a'
>>> d[3]
'c'
>>> d[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 5

As shown by the example above, a key error is raised if the key to lookup is not in the dict object.

The len function can be applied to dict objects, returning the number of items in the dict.

>>> len({1: 'a', 2: 'b', 3: 'c'})
3
>>> len ({})
0

Conversion between dicts and other types. Dicts can be converted to strings, Boolean objects, tuples and lists, but not to numbers. The string conversion of a dict object represents the literal form of the dict object.

The Boolean conversion of a dict is False only when the dict is empty, and True otherwise.

>>> bool({1: 'a', 2: 'b', 3: 'c'})
True
>>> bool ({1: 1})
True
>>> bool ({})
False

The tuple and list conversions of a dict object consist of all the keys in the dict object.

>>> d = {1: 1.0, 2: 9, 3: 8}
>>> tuple(d)
(1, 2, 3)
>>> list(d)
[1, 2, 3]

Lists and tuples can be converted to dicts using the dict function, but numbers, strings, or Boolean objects cannot. To be convertable to a dict, a tuple or list must be a sequence (key, value) pairs.

>>> d1 = dict(((3, 'a'), (2, 'b'), (3, 'c')))
>>> d2 = dict([(3, 'a'), (2, 'b'), (3, 'c')])
>>> d1
{2: 'b', 3: 'c'}
>>> d1 == d2
True

Check your understanding

Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

© Copyright 2024 GS Ng.

Next Section - 10.2 Dict Modification