Dictionaries

Dictionaries are extremely flexible data structures. They store pairs of elements where a key is mapped to a value.

Any type of object is supported as a value but, due to the implementation of dictionaries, keys must be immutable (hashable to be more precise). On that account, we cannot use a list as a key for instance.

As with lists, both keys and values can be heterogeneous.

Representation

Dictionaries can be constructed in many different ways. This example taken from the Python documentation builds the exact same dictionary and is pretty self-explanatory.

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict([('two', 2), ('one', 1), ('three', 3)])
d = dict({'three': 3, 'one': 1, 'two': 2})

Access and update

Given a key we can efficiently access its associated value with the indexing operator []:

>>> d = {'a': 1, 'b': [2, 3], 'c': 'four'}
>>> d['c']
'four'
>>> d['c'] += ' hundred'
>>> d['c']
'four hundred'

When iterating a dictionary it is important to keep in mind that the order in a dictionary is not determined (but it keeps the same until we modify it). This is the most direct way to iterate it,

for key in d:
    print(key, d[key])

which will print

a 1
b [2, 3]
c four

With the get() method, we can return a default value in case the key is not in the dictionary:

>>> d['f']
KeyError: 'f'
>>> d.get('f', 'some default')
'some default'

With del we can erase a key, together with its information:

>>> del d['c']
>>> d
{'a': 1, 'b': [2, 3]}

Imagine we wanted to count the number of occurrences of each word in a given text. A possible solution that uses dictionaries is

text = 'some text with words and some repeated words'
d = {}
for word in text.split():
    if word in d:
        d[word] += 1
    else: # First occurrence of word
        d[word] = 1
print(d)

which will output

{'some': 2, 'text': 1, 'with': 1, 'words': 2, 'and': 1, 'repeated': 1}

To make our code even simpler, we can rely on the get() method:

for word in text.split():
    d[word] = d.get(word, 0) + 1







Lliçons.jutge.org
Víctor Adell
Universitat Politècnica de Catalunya, 2019

Prohibit copiar. Tots els drets reservats.
No copy allowed. All rights reserved.