Section 11.7 Using Tuples as Keys in Dictionaries
Because tuples are hashable and lists are not, if we want to create a composite key to use in a dictionary we must use a tuple as the key.
We would encounter a composite key if we wanted to create a telephone directory that maps from last-name, first-name pairs to telephone numbers. Assuming that we have defined the variables last
, first
, and number
, we could write a dictionary assignment statement as follows:
directory[last, first] = number
Checkpoint 11.7.1.
Write code to create a dictionary called ‘d1', and in it give the tuple (1, ‘a') a value of “tuple”.
Checkpoint 11.7.2.
11-9-2: Which of these options can be keys of a dictionary? Select all that apply.
Dictionaries
Incorrect! Dictionaries cannot be the keys of other dictionaries. Try again.
Tuples
Correct! It is fine to use tuples as keys in a dictionary.
Strings
Correct! Strings are used as keys of dictionaries all the time!
Integers
Correct! Integers are perfectly acceptable to be keys of dictionaries.
Lists
Incorrect! Lists cannot be used as the keys of dictionaries. Try again.
The expression in brackets is a tuple. We could use tuple assignment in a for
loop to traverse this dictionary.
for last, first in directory:
print(first, last, directory[last, first])
This loop traverses the keys in directory
, which are tuples. It assigns the elements of each tuple to last
and first
, then prints the name and corresponding telephone number.
Checkpoint 11.7.3.
11-9-3: Which of the following lines of code correctly prints the value associated with (‘Go', ‘Blue')? Select all that apply.
my_dict = {}
my_dict[('Go', 'Blue')] = True
my_dict['Go']
Incorrect! You need both values in the tuple for the dictionary to recognize it as the correct key. Try again.
my_dict['Blue']
Incorrect! You need both values in the tuple for the dictionary to recognize it as the correct key. Try again.
my_dict['Go', 'Blue']
Correct! In this case, the parentheses of the tuple are not required in order to properly call its value.
my_dict[('Go', 'Blue')]
Correct! This is one way to grab the value associated with the tuple.