Accessing a Dictionary
You need to find and change entries in a dictionary.
Use the Python [] notation. Use the key of the entry to which you need access inside the brackets:
>>> phone_numbers = {‘Simon’:’01234 567899′, ‘Jane’:’01234 666666′} >>> phone_numbers[‘Simon’] ‘01234 567899’ >>> phone_numbers[‘Jane’] ‘01234 666666’ |
Discussion
If you use a key that is not present in the dictionary, you will get a key error. For example:
{‘b_key1’: {‘key2’: 2, ‘key1’: ‘value1’}} >>> phone_numbers = {‘Simon’:’01234 567899′, ‘Jane’:’01234 666666′} >>> phone_numbers[‘Phil’] Traceback (most recent call last): File “<stdin>”, line 1, in <module> KeyError: ‘Phil’ >>> |
As well as using the [] notation to read values from a dictionary, you can also use it to add new values or overwrite existing ones.
The following example adds a new entry to the dictionary with a key of Pete and a value of 01234 777555:
>>> phone_numbers[‘Pete’] = ‘01234 777555’ >>> phone_numbers[‘Pete’] ‘01234 777555’ |
If the key is not in use in the dictionary, a new entry is automatically added. If the key is already present, then whatever value was there before will be overwritten by the new value.
This is in contrast to trying to read a value from the dictionary, where an unknown key will cause an error.
See Also
All the recipes between Recipes 6.12 and 6.15 involve the use of dictionaries.
For information on handling errors, see Recipe 7.10.