Python Dictionaries
Python Dictionaries
1 Dictionaries
Concept: A dictionary is an object that stores a collection of data. Each element in a dictionary
has two parts: a key and a value. You use a key to locate a specific value.
When you hear the word “dictionary,” you probably think about a large book such as the Merriam-
Webster dictionary, containing words and their definitions. If you want to know the meaning of a
particular word, you locate it in the dictionary to find its definition.
In Python, a dictionary is an object that stores a collection of data. Each element that is stored in
a dictionary has two parts: a key and a value. In fact, dictionary elements are commonly referred
to as key-value pairs. When you want to retrieve a specific value from a dictionary, you use the
key that is associated with that value. This is similar to the process of looking up a word in the
Merriam-Webster dictionary, where the words are keys and the definitions are values.
For example, suppose each employee in a company has an ID number, and we want to write a
program that lets us look up an employee’s name by entering that employee’s ID number. We
could create a dictionary in which each element contains an employee ID number as the key and
that employee’s name as the value. If we know an employee’s ID number, then we can retrieve that
employee’s name.
Another example would be a program that lets us enter a person’s name and gives us that person’s
phone number. The program could use a dictionary in which each element contains a person’s
name as the key and that person’s phone number as the value. If we know a person’s name, then
we can retrieve that person’s phone number.
Note: Key-value pairs are often referred to as mappings because each key is mapped to a value.
This statement creates a dictionary and assigns it to the phonebook variable. The dictionary
contains the following three elements:
• The first element is ‘Chris’:‘555−1111’. In this element the key is ‘Chris’ and the value is
‘555−1111’.
1
• The second element is ‘Katie’:‘555−2222’. In this element the key is ‘Katie’ and the value is
‘555−2222’.
• The third element is ‘Joanne’:‘555−3333’. In this element the key is ‘Joanne’ and the value
is ‘555−3333’.
In this example the keys and the values are strings. The values in a dictionary can be objects of
any type, but the keys must be immutable objects. For example, keys can be strings, integers,
floating-point values, or tuples. Keys cannot be lists or any other type of immutable object.
[2]: phonebook
Notice that the order in which the elements are displayed is different than the order in which they
were created. This illustrates how dictionaries are not sequences, like lists, tuples, and strings.
As a result, you cannot use a numeric index to retrieve a value by its position from a dictionary.
Instead, you use a key to retrieve a value.
To retrieve a value from a dictionary, you simply write an expression in the following general format:
dictionary_name[key]
KeyError: If the key exists in the dictionary, the expression returns the value that is associated
with the key. If the key does not exist, a KeyError exception is raised. The following interactive
session demonstrates:
[4]: phonebook['Chris']
[4]: '555−1111'
[5]: phonebook['Joanne']
[5]: '555-3333'
[6]: phonebook['Katie']
[6]: '555−2222'
[7]: phonebook['Kathryn']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-7-df7a314d232f> in <module>
----> 1 phonebook['Kathryn']
2
KeyError: 'Kathryn'
1.3 Using the in and not in Operators to Test for a Value in a Dictionary
As previously demonstrated, a KeyError exception is raised if you try to retrieve a value from a
dictionary using a nonexistent key. To prevent such an exception, you can use the in operator to
determine whether a key exists before you try to use it to retrieve a value. The following interactive
session demonstrates:
555−1111
You can also use the not in operator to determine whether a key does not exist, as demonstrated
in the following session:
[12]: phonebook
3
1.5 Deleting Elements
You can delete an existing key-value pair from a dictionary with the del statement. Here is the
general format:
del dictionary_name[key]
[13]: phonebook
[15]: phonebook
[20]: test_scores
[21]: test_scores['Sophie']
4
[22]: kayla_scores = test_scores['Kayla']
[23]: print(kayla_scores)
statement
etc.
[24]: phonebook
Katie
Joanne
Joe
Katie 555−2222
Joanne 555-3333
Joe 555−0123
5
[28]: phonebook
[28]: {}
555−2222
[31]: phonebook.items()
[32]: phonebook
[33]: phonebook.keys()
6
dictionary.pop(key, default)
[36]: phone_num
[36]: '555−1111'
[39]: phone_num
[40]: phonebook
[42]: phonebook
[44]: print(key,value)
Joanne 555−3333
7
[45]: phonebook
[47]: phonebook.values()
[ ]: