Dictionaries
What is a dictionary?
A dictionary is a lot like a list, but instead of accessing values using an index, we use something called a key. A key is a name that we use to access a value in our dictionary. Every key inside a dictionary is unique, meaning we can reliably access a specific value using a given key.
Let's look at an example. Perhaps we want to create a collection which keeps track of our friends' ages. We could use a list, but we would have to remember which person each age belongs to. That's not very convenient. Using a dictionary, we can store each friend's age alongside that friend's name.
To create a dictionary we use curly braces, instead of the square brackets we used to create a list. Each element in the dictionary must be made up of a key-value pair, separated by a colon. Like with lists, each dictionary element is separated by a comma:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
Excellent! Now to find out Rolf's age, we just need to look up the value for the key "Rolf"
. So, how do we do that?
Accessing a value stored in a dictionary
Accessing the value associated with a key is very similar to accessing the index of a list.
For example, we could access Rolf's age by doing:
print(friend_ages["Rolf"]) # 24
So what you must do to access the value associated with the key "Rolf"
is use square brackets (subscript notation) and inside the square brackets place the key that you want to retrieve a value for.
If you try to access a key that doesn't exist (e.g. friend_ages["Bob"]
), you'll get a KeyError
.
It will look like this:
KeyError: 'Bob'
Up to Python 3.7 the keys in a dictionary were not guaranteed to be in any specific order. In Python 3.7 the ordering has changed, and now dictionaries keep the order of the keys when you created it. However I almost never have to worry about order of keys in a dictionary, so I would recommend not getting too caught up in it.
Adding a new key-value pair to a dictionary
Adding a new key-value pair is very straightforward! All you have to do is assign to the accessed key, like so:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
friend_ages["Bob"] = 20
print(friend_ages) # {'Rolf': 24, 'Adam': 30, 'Anne': 27, 'Bob': 20}
That is also how you can modify an existing value associated to a key.
friend_ages["Rolf"] = 25
print(friend_ages) # {'Rolf': 25, 'Adam': 30, 'Anne': 27}
Try it out on this code editor!
Adding multiple items at once
If you want to add lots of key-value pairs to a dictionary in one go, Python has a handy method for this called update
.
To use the update
method, we start with the dictionary we want to update, followed immediately by .update()
. We can then put a second dictionary inside the parentheses of the update
method:
dict_1 = {
"Rolf": 25
}
dict_2 = {
"Adam": 30,
"Anne": 27
}
dict_1.update(dict_2) # {'Rolf': 25, 'Adam': 30, 'Anne': 27}
Instead of passing in a dictionary, we can instead pass in an iterable type containing pairs of values. A list happens to be an iterable type. We know this because we can iterate over the values in a list using a for or while loop.
We can therefore use a list of lists as our argument to update, giving us the exact same result as above:
dict_1 = {
"Rolf": 25
}
dict_1.update([["Adam", 30], ["Anne", 27]])
Here the outer list allows us to iterate over our pairs of values as a single group, while the inner lists are just containers for our key-value pairs.
Finally, we can update a list using keywords. In this case, we provide a name and value for each item we want to add, and separate each pair with a comma:
dict_1 = {
"Rolf": 25
}
dict_1.update(Adam=30, Anne=27)
Once again, this provides the exact same result as above.
We're going to be taking a much closer look at functions in the next sections of this chapter, so don't worry if you're not 100% clear about what's going on. You should be able to understand all of the tools we used here after you've learnt about functions.
Copying dictionaries
Dictionaries are very similar to lists, in that if you do this:
friend_names_to_info = {
"Rolf": {"name": "Rolf Smith", "age": 24},
"Adam": {"name": "Adam Wool", "age": 30},
"Anne": {"name": "Anne Pun", "age": 27}
}
friends_abroad = friend_names_to_info
friends_abroad["Bob"] = {"name": "Bob Sponge", "age": 20}
Both friends_abroad
and friend_names_to_info
will end up with "Bob"
in them—they are the same dictionary.
I don't think I've ever encountered the need to copy a dictionary like this, but you can do:
friend_names_to_info = {
"Rolf": {"name": "Rolf Smith", "age": 24},
"Adam": {"name": "Adam Wool", "age": 30},
"Anne": {"name": "Anne Pun", "age": 27}
}
friends_abroad = friend_names_to_info.copy()
friends_abroad["Bob"] = {"name": "Bob Sponge", "age": 20}
However, like in lists, this creates a shallow copy. Modifying any of the inner dictionaries will still change it in both variables.
Can you have multiple similar dictionaries?
Similarly to what we talked about in the last chapter, if you find yourself having multiple variables with very similar dictionaries (i.e. they have the same keys), it's probably best to put them in a list.
For example, you could have a list of your friends:
friends = [
{"name": "Rolf Smith", "age": 24},
{"name": "Adam Wool", "age": 30},
{"name": "Anne Pun", "age": 27}
]
And that would be much better than having three separate variables.
Use cases for dictionaries
The main purpose of a dictionary is to allow you to easily access the values (in case of the example above, the ages) given you only know the keys (the names of friends).
Said in another way, if you know the friend name you can easily find out their age by using that dictionary.
Other examples where a dictionary might be useful:
- A dictionary that maps user IDs to their details;
- A dictionary that maps blog authors to their blog addresses;
- A dictionary that maps coffee bean names to coffee bean information.
Must the keys be strings?
No, the keys can also be numbers or other immutable types, but most often they are strings.
Can you have duplicate keys?
No, in dictionaries the keys are unique. You can have duplicate values though, that's totally fine.
Must the values be strings?
No, the values can be anything you want! They are often strings, but they can be numbers, lists, dictionaries, or anything else.
Extra reading
If you'd like to learn more about sets and why they can be really helpful, I recommend this part of our "Collections" blog post: http://blog.tecladocode.com/learn-python-day-7-collections/#sets. The rest of the post can also be relevant to you!