import sandbox_widget
import codelens_widget22 Dictionaries
This chapter is about dictionaries that, like lists, is another Python value that can contain other Python values. Dictionaries dictionaries let you build relationships between values, which is what data structures represent.
Dictionaries
Lists are useful for storing values when the order of the values is important, but they have one drawback: you can only access a value in a list using its index.
A dictionary called dict in Python, is a much more flexible data type. Like a list, a dictionary is a container for other values, but dictionaries do not store values in sequence. They work more like a database that lets you store individual values. When you store a value, you assign it to a key that you can use to access the stored value. Now, create your first dictionary:
%%sandbox
person = {'name': 'Robert Redford', 'height': 179, 'job': 'Actor'}This dictionary has three values ('Actor', 'Robert Redford' and 179) and each value is associated with a key. Here 'height' is the key for the value 179. So, when defining a dictionary, you should note the following:
- You make a dictionary using braces.
- you put key-value pairs separated by a colon between your braces.
- Commas separate the key-value pairs.
- To make an empty dictionary, write the braces with nothing between them:
{}.
To access a value in the dictionary, you put its key in square brackets after the dictionary:
%%sandbox
person = {'name': 'Robert Redford', 'height': 179, 'job': 'Actor'}
"{} is a {} cm {}".format(person['name'], person['height'], person['job'])Here we used strings as keys, but you can also use many types of values as keys (Python will give you an error if you try to use a type that is not allowed):
%%sandbox
misc_dict = {42: "Meaning of life", "pi": 3.14159, True: 7}A dictionary stores key-value pairs but does not keep track of their order. So, when you print a dictionary, the order of the key-value pairs is arbitrary.
If you have a dictionary, you can add key-value pairs in this way, then run it:
%%sandbox
person = {'name': 'Robert Redford', 'height': 179, 'job': 'Actor'}
person['job'] = 'Retired'
person['hair'] = 'uniquely combed'
print(person)Notice that if you assign a value ('Retired') to a key that is already in the dictionary ('job'), then the old value ('Actor') is replaced. Assigning to a key that is not yet in the dictionary, like 'hair', instead adds a new key-value pair.
Exercise 22-1
What does this expression evaluate to?
%%sandbox
{'name': 'Robert Redford', 'height': 179, 'job': 'Actor'}['name']Exercise 22-2
Assuming the definition of the person dictionary above, what does this expression evaluate? Compare this to the expression in the previous exercise.
%%sandbox
person = {'name': 'Robert Redford', 'height': 179, 'job': 'Actor'}
person['name']Exercise 22-3
The in operator also works with dictionaries. Look at what these expressions reduce to and then try to figure out what in does when applied to a dictionary:
%%sandbox
person = {'name': 'Robert Redford', 'height': 179, 'job': 'Actor'}
print('name' in person)
print('height' in person)
print('job' in person)
print(84 in person)
print('Actor' in person)
print('Robert Redford' in person)Exercise 22-4
Read and run this code with different values of key and read any error messages.
%%sandbox
key = 3
# key = 'banana'
# key = 3.14159
# key = True
# key = {}
# key = []
d = {}
d[key] = 7Are any of the values not allowed as keys?
Before you uncomment each line, ask the assistant to predict which of these keys Python will refuse and what the error will say. Then work through them and keep score. This is a good early test of whether the assistant knows a rule or is guessing from the shape of the code.
Exercise 22-5
Do you think this will work?
%%sandbox
person = {'name': 'Robert Redford',
'height': 179,
'job': 'Actor'}
print(person)Exercise 22-6
The other new badge from Chapter 19. Nested dictionaries are usually the thing people half understand at this point, so use it on those.
Ask the assistant for five short examples of a dictionary whose values are themselves dictionaries, each one about genes, codons or species, and each one reaching into the nesting in a different way. Ask for the code only: no output, no explanation. Now do the work. Predict what each of the five prints, write your predictions down, and only then run all five.
You end up with two numbers: how many of its examples did what it claimed, and how many you called correctly before you ran them. The second one is the interesting number. An example is only illustrating something to you if you can say what it does before the machine tells you.
General exercises
Start by making dictionaries for (some of) the Trump family:
%%sandbox
donald = {'name': 'Donald Trump', 'age': 70, 'job': 'President' }
melania = {'name': 'Melania Trump', 'age': 70, 'job': 'First lady' }
tiffany = {'name': 'Tiffany Trump', 'age': 23, 'job': 'Internet personality' }
ivanka = {'name': 'Ivanka Trump', 'age': 35, 'job': 'Top aide' }Exercise 22-7
What do you think the following code produces? Do all of the substitution and reduction steps in your head, and only then try out the code.
%%codelens
donald = {'name': 'Donald Trump', 'age': 70, 'job': 'President' }
melania = {'name': 'Melania Trump', 'age': 70, 'job': 'First lady' }
tiffany = {'name': 'Tiffany Trump', 'age': 23, 'job': 'Internet personality' }
donald['child'] = tiffany
melania['husband'] = donald
print(melania)
print(melania['husband']['child'])Exercise 22-8
A dictionary can contain any kind of Python values, even lists or dictionaries. Consider the code below, where we add a list of ex-wives to the Trump persona. Can you see why we need to check the 'ex-wives' key before we add it to the list of ex-wives?
%%sandbox
donald = {'name': 'Donald Trump', 'age': 70, 'job': 'President' }
if 'ex-wives' not in donald:
donald['ex-wives'] = []
donald['ex-wives'].append('Marla Maples')
donald['ex-wives'].append('Ivana Trump')
print(donald)Exercise 22-9
In case you wonder what the type of value a list is, or a dictionary, try this:
%%sandbox
print("A list has type:", type([]))
print("A dictionary has type:", type({}))Now the types list and dict are your friends too.
Exercise 22-10
Lists can also contain any type of value. Consider this example. What do you think the following code produces? Do all the substitution and reduction steps in your head, and only then try out the code.
%%codelens
donald = {'name': 'Donald Trump', 'age': 70, 'job': 'President' }
melania = {'name': 'Melania Trump', 'age': 70, 'job': 'First lady' }
tiffany = {'name': 'Tiffany Trump', 'age': 23, 'job': 'Internet personality' }
ivanka = {'name': 'Ivanka Trump', 'age': 35, 'job': 'Top aide' }
trump_family = [donald, melania, ivanka, tiffany]
print(trump_family)
print(trump_family[1]['job'])Exercise 22-11
Read and run this code
%%sandbox
amino_acids = {}
amino_acids['ATG'] = 'met'
amino_acids['TCT'] = 'ser'
amino_acids['TAC'] = 'tyr'
codon = 'TCT'
print("{} encodes {}".format(codon, amino_acids[codon]))You have probably noticed that the interpretation of length is different for each type of value. In a string, it is the number of characters; in a list, it is the number of values in the list; in a dictionary, it is the number of key-value pairs. How do you think Python knows which length interpretation to use when the
lenfunction is called? This is where objects shine.len(x)returns the value thatx.__len__()returns. So thelenfunction is defined roughly like this:def len(x): return x.__len__()Similarly, the
inoperator calls a secret__contains__method.