dict.py
= {"cat": "meow", "dog": "woof", "horse": "neigh"}
sounds
= sounds["cat"]
cat_sound
print(cat_sound)
meow
Lists let you store lots of variables, and to access them by their location in the list. However, there are times when you may want to access them using more complex relationships. One example is a dictionary, which lets you store variables and access them using a key.
Dictionaries in Python are created using curly brackets. Make a new file called dict.py
with the below code and run it:
dict.py
= {"cat": "meow", "dog": "woof", "horse": "neigh"}
sounds
= sounds["cat"]
cat_sound
print(cat_sound)
meow
What we did here was create a dictionary on the first line. A dictionary is created using curly brackets ({}
). The dictionary we created here has three items in it where each item comprises a key and a value. The value is the data that we want to keep hold of and the key is the label we use to find the data we want. The key and value are separated by a colon and each key-value pair is separated by a comma.
On the second line we access the data in the dictionary sounds
. Like lists we use the square brackets to ask questions of our data. In this case we are asking the dictionary to give us the value associated with the key "cat"
and so it will return to us meow
.
Since dictionaries can be quite large and it can sometimes be hard to see which parts are keys and which are values, it is possible to write dictionaries over multiple lines, one line per key-value item as in:
dict.py
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
= sounds["cat"]
cat_sound
print(cat_sound)
As with lists, dictionaries are dynamic so we can add entries into a dictionary.
Let’s say that we want to add in a new sound for a cow into our sounds
dictionary. The key that the data will have will be cow
and the value will be moo
. To do so we put sounds["cow"]
on the left-hand side of a variable assignment expression, as if we’re making a new variable. On the right goes the data that we want to put into the dictionary:
dict.py
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
"cow"] = "moo"
sounds[
print(sounds)
This is saying that we want the value "moo"
associated with the key "cow"
in the dictionary sounds
.
Running it, we see:
Terminal/Command Prompt
python dict.py
{'cat': 'meow', 'dog': 'woof', 'horse': 'neigh', 'cow': 'moo'}
When discussing for
loops you were told that Python allows you to loop over lots of different types of data such as lists, strings and range
s. We can add dictionaries to that set.
To discover how it works, let’s do the naïve thing first and just see what happens when we loop over a dictionary:
dict.py
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
for animal in sounds:
print(animal)
cat
dog
horse
You will recognise those as the keys from the dictionary. So, it seems that when looping over a dictionary we will be given the keys.
What if, for example, you wanted to loop over the values instead. Well, there is a method on dictionaries called values
which gives you just those so that you can loop over them:
dict.py
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
for sound in sounds.values():
print(sound)
meow
woof
neigh
If we want to loop over the dictionary and get both the keys and the values, there is a method called items
. Since it will be giving us two things each loop iteration, we’ll have to use the same trick as we did with enumerate
and give two variable names in the for
loop declaration:
dict.py
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
for animal, sound in sounds.items():
print(animal, "goes", sound)
cat goes meow
dog goes woof
horse goes neigh
The items
method gives us two pieces of data where the first is always the key and the second if always the value. We give the keys the name animal
and the values the name sound
. We can then use both those variables in the loop body.
Dictionaries can be used for any key-value mapping. The example above was a mapping of an animal species (as a string) to an animal sound (as a string). You can use any data type you wish as the value in a dictionary, for example you might make a dictionary containing the population of some cities in millions (as a float):
= {
census "London": 8.615,
"Paris": 2.244,
"Rome": 2.627,
}
or one which contains a list of authors as the key (as a string) and their books (as a list of strings):
= {
bookshelf "Terry Pratchett": ["Mort", "Jingo", "Truckers"],
"Jane Austen": ["Sense and Sensibility", "Pride and Prejudice"],
"Charles Dickens": ["Oliver Twist"],
}