Question 6.13: Accessing a Dictionary You need to find and change entries i......

Accessing a Dictionary

You need to find and change entries in a dictionary.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 6.15

Verified Answer:

Use the for command to iterate over the keys of th...
Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.11

Verified Answer:

Use the Python language feature called comprehensi...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.10

Verified Answer:

Use the [:] Python language construction. The foll...
Question: 6.9

Verified Answer:

Use the sort Python language command: >>&...
Question: 6.7

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...
Question: 6.3

Verified Answer:

Use the len Python function. For example: >&...