Mutability of dictionaries

The keys in a dictionary should be immutable, although the values can be modified. Here's a dictionary which maps the element symbol to a list of mass numbers for different isotopes of that element:

>>> m = {'H': [1, 2, 3],
... 'He': [3, 4],
... 'Li': [6, 7],
... 'Be': [7, 9, 10],
... 'B': [10, 11],
... 'C': [11, 12, 13, 14]}

See how we split the dictionary literal over multiple lines. That's allowed because the curly braces for the dictionary literal are open.

Our string keys are immutable, which is a good thing for correct functioning of the dictionary. But there's no problem with modifying the dictionary values in the event that we discover some new isotopes:

>>> m['H'] += [4, 5, 6, 7]
>>> m
{'H': [1, 2, 3, 4, 5, 6, 7], 'Li': [6, 7], 'C': [11, 12, 13, 14],
'B':
[10, 11], 'He': [3, 4], 'Be': [7, 9, 10]}

Here, the augmented assignment operator is applied to the list object accessed through the 'H' (for hydrogen) key; the dictionary is not being modified.

Of course, the dictionary itself is mutable; we know we can add new items:

>>> m['N'] = [13, 14, 15]

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset