Skip to content

Informatics Practices · Ch 4 — Working with Lists and Dictionaries

Dictionaries are Mutable

4.6.4

Dictionaries are Mutable

Like lists — and unlike strings and tuples — dictionaries are mutable: the contents of a dictionary can be changed after it has been created. There is no need to build a fresh dictionary every time the data changes; the existing one can be updated in place. Two kinds of change follow from this, and both use the same assignment syntax.

Adding a new item

Assigning a value to a key that is not yet in the dictionary creates a brand-new item. The dictionary simply grows by one key-value pair:

>>> dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}

'Meena' was not among the keys, so dict1['Meena'] = 78 adds the item 'Meena': 78 to the dictionary — the four original students are untouched and a fifth item now exists.

Modifying an existing item

If the key already exists, the same assignment does not add anything; it overwrites the key's value with the new one. The dictionary keeps the same set of keys — only the value bound to that key changes:

>>> dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
>>> dict1['Suhel'] = 93.5        # marks of Suhel changed to 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}

Here Suhel's marks change from 92 to 93.5. Nothing else moves: the dictionary still has four items, and the other three key-value pairs are exactly as before. Notice that this is possible only because keys are unique — since 'Suhel' can occur just once, Python knows unambiguously which value to replace. …