In this article, let us learn about Dictionaries in Python. Let us see how to create, edit and use Dictionaries in our projects with the help of some examples.
If you are a complete beginner skip the following section and go to the next one by clicking on “Python Dictionary: The Basic” in the Table of contents below. If you are just looking to refresh your memories read on!
Python Dictionary in a Nutshell
A dictionary is an essential data structure in python. It is used to store key-value pairs.
The syntax to define a dictionary in python is as follows
dict_name = {key1:value1, key2:value2, key3:value3}
The example below shows how to use this syntax.
dict1 = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
Not all keys and values need to be strings. In python the only condition is that all keys should be “unique” and of an immutable type (e.g. string, integer) whereas values can be of any type as shown in Example#2 below.
Toronto = {"country":"Canada", "population":270000, "attractions":[ "CN Tower", "Casa Loma"], "country_capital":True}
Python Dictionary: Cheatsheet
We will use Example-1 above for working through this section. For your convenience here it is again
dict1 = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
Manipulate items using square brackets “[ ]” notation
The table below shows how to manipulate items in a dictionary using the square brackets notation.
Example Code | Comments |
---|---|
>>> dict1[‘a’] ‘apple’ | Get the value associated with a key |
>>> dict1[‘d’] = ‘doll’ >>> dict1 {‘a’: ‘apple’, ‘b’: ‘ball’, ‘c’: ‘cat’, ‘d’: ‘doll’} | Insert a new key-value pair into the dictionary |
>> dict1[‘b’] = ‘bat’ >>> dict1 {‘a’: ‘apple’, ‘b’: ‘bat’, ‘c’: ‘cat’, ‘d’: ‘doll’} | Update the value associated with the given key |
In-Built Functions and Operators to use with Dictionaries
The table below shows some of the useful operators and built-in functions to use with Dictionaries in Python.
Example Code | Comments |
---|---|
>>> len(dict1) 3 | The in-built function len() is used to get the number of items in a given dictionary |
>>> if ‘b’ in dict1: … print(“b is a key in dict1”) b is a key in dict1 | Check if the specified key is present in the given dictionary using the “in” operator |
>>> if ‘d’ not in dict1: … print(“The key ‘d’ is not present in dict1”) The key ‘d’ is not present in dict1 | Check if the specified key is absent in the given dictionary using the “not in” operator |
Methods that come with Dictionaries
The table below shows some of the useful methods that come with the dictionary class
Code | Comments |
---|---|
>>> dict1.get(‘c’) ‘cat’ | Get the value associated with the key given in the argument |
>>> dict1.pop(‘b’) ‘ball’ >>> dict1 {‘a’: ‘apple’, ‘c’: ‘cat’} | Remove the item with the passed-in key and returns its value. |
>>> dict1.popitem() (‘c’, ‘cat’) >>> dict1 {‘a’: ‘apple’} | Remove and return the item added last. (‘c’: ‘cat’) in our case. |
>>> dict1.clear() >>> dict1 { } | Remove all the items present in dict1. After this statement dict1 becomes an empty dictionary |
>>> dict1.items() dict_items([(‘a’, ‘apple’), (‘b’, ‘ball’), (‘c’, ‘cat’)]) | Get all the items in the dictionary as a dict_items object |
>>> dict1.keys() dict_keys([‘a’, ‘b’, ‘c’]) | Get all the keys in the dictionary as a dict_keys object |
>>> dict1.values() dict_values([‘apple’, ‘ball’, ‘cat’]) | Get all the values in the dictionary as a dict_values object |
>>> dict2 = dict1.copy() >>> dict2 {‘a’: ‘apple’, ‘b’: ‘ball’, ‘c’: ‘cat’} | Make a copy of dict1 and store it in another object dict2 |
>>> dict1.setdefault(‘d’, ‘doll’) ‘doll’ >>> dict1 {‘a’: ‘apple’, ‘b’: ‘ball’, ‘c’: ‘cat’, ‘d’: ‘doll’} | If the passed-in key is not present in the dictionary, add the given key-value pair to that dictionary |
>>> dict2 = {‘e’: ‘elephant’, ‘f’: ‘frog’} >>> dict1.update(dict2) >>> dict1 {‘a’: ‘apple’, ‘b’: ‘ball’, ‘c’: ‘cat’, ‘d’: ‘doll’, ‘e’: ‘elephant’, ‘f’: ‘frog’} | Add all elements in dict2 to dict1. After these statements |
Python Dictionary: The Basics
This article is specifically prepared to keep beginners in mind, so if you are feeling confused, forget that you ever read the section above, find a quiet place, focus for the next few minutes, and read through this article. Once you are finished come back and read the section above, I guarantee that it will make more sense!
The very fact that you have googled and found this article shows that you are one of the few who really wish to understand Python at a deeper level, and we are here to support you in your journey to become a Python craftsman!
With that being said, let’s start understanding dictionaries by going through the following topics:
- What are dictionaries?
- How to define a dictionary
- Assigning and Manipulating dictionary items
- Accessing dictionary items
- Methods on Dictionaries
- Conclusion
Let’s start!
What are dictionaries?
I am sure we all have used a dictionary to look up different words right? Well, the dictionaries in Python are similar in a sense!
Just like how there is a meaning/explanation for each word in a real-world dictionary, there is a value for a key in a Python dictionary.
Real world dictionary maps a word with its meaning/explanation,
Python dictionary maps a key to its value!
Let us have another look at the example we saw previously.
dict1 = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
Here ‘a‘, ‘b‘ and ‘c‘ are the keys and ‘apple‘, ‘ball‘, and ‘cat‘ are the values.
Let us take a look at another example (This time a more tasty one!) to make things more clear.
I have a list of my favorite dishes from around the world and I want to assign it to their home country. I am going to format my data into a dictionary as follows:
Dishes = {
"Japan": "Sushi",
"China": "Chinese Noodles",
"India": "Roti",
"Turkey": "Baklava"
}
Ignoring the mouth-watering dishes, this is how we create and define a dictionary. For the visual learners amongst you, the following diagram visualizes the dictionary we just defined:
You have already seen the creation of a couple of dictionaries already, but when the time comes for you to create one on your own, you will need to know the correct syntax to use.
Syntax to Define a Dictionary
The syntax used to create a dictionary is pretty simple. Let’s make one called countries:
- All dictionaries open and close with curly brackets
countries = {}
With the line of code above, we have already created a dictionary called “countries“!
It is still an empty dictionary, since we haven’t added any items yet, let us go ahead and add some items, shall we?
- Items should always be in pairs separated by a colon “:”
countries = {'Asia':'Bangladesh'}
There you go! We have added the continent Asia which is the key here and assigned it to the value ‘Bangladesh‘
- If you wish to add more keys, just use a comma to separate them
countries = {'Asia':'Bangladesh','Europe':'Estonia', 'North America':'Canada'}
The syntax used above is shown in the pic below.
Just write a comma-separated list of key:value pairs bounded by curly-braces, simple as that!
Advanced
You can also create a dictionary using the dictionary’s constructor: dict()
The way it works is by accepting a collection of key-value pairs.
A list containing tuples of key-value pairs is a valid way to construct a dictionary through its constructor, for example:
list1 = [("Guido van Rossum", "Python "),
("James Gosling", "Java")]
A tuple containing lists of key-value pairs is also valid!
Using this method I am going to create the same dictionary ‘Dishes’ using dict():
Dishes = dict([
("Japan", "Sushi"),
("China", "Chinese Noodles"),
("India", "Roti"),
("Turkey", "Baklava")
])
One thing you need to remember is that
Every key must be unique
This means there can’t be two identical keys. You can use any strings or integers as keys. As for values, there are no restrictions on them and your values can be Lists, Sets, or whatever data-type your code needs!
Advanced
You can use any immutable type as key not just strings and integers. This means tuples are allowed to be keys whereas lists and sets as not. Explaining this is way beyond the scope of this article, I suggest googling “what are immutable types in python” if you wish to learn more.
In other languages such as Java, C#, etc. Dictionaries are referred to using complicated names such as associative arrays and hash table, but Python being a language which aims to be simple, uses the name “Dictionary” to keep it easy to understand and use!
Now that we know how to create a dictionary, next we need to learn how to use the dictionary we created in our code!
Accessing dictionary items
Unlike lists, sets, and tuples, we don’t use a numerical index to access a dictionary item, we instead use the key to access its respective value.
If I wish to print the value associated with the key ‘Japan’, I will do it by executing the following statement:
>>> Dishes = { "Japan": "Sushi", "China": "Chinese Noodles", "India": "Roti", "Turkey": "Baklava"}
>>> print(Dishes['Japan'])
[Sushi, 'Ramen']
The following syntax prints the value of the key I have specified.
print(dict_name[key_name])
In case of passing a statement where the key does not exist, we expectedly will encounter an error
If I want to get an Indonesian dish from ‘Dishes’, we will encounter a ‘KeyError ‘
>>> Dishes = { "Japan": "Sushi", "China": "Chinese Noodles", "India": "Roti", "Turkey": "Baklava"}
>>> print(Dishes['Indonesia'])
Traceback (most recent call last):
File "main.py", line 20, in <module>
print(Dishes['Indonesia'])
KeyError: 'Indonesia'
One interesting thing to note is that passing a numerical index also results in the same error!
>>> Dishes = { "Japan": "Sushi", "China": "Chinese Noodles", "India": "Roti", "Turkey": "Baklava"}
>>> print(Dishes[2])
Traceback (most recent call last):
File "main.py", line 20, in <module>
print(Dishes[2])
KeyError: 2
The error is the same for both because Python considers whatever you pass inside the square brackets as a key to the dictionary. In fact, Python actually allows dictionaries to have numerical keys like follows:
>>> superheroes = { 7:'Spider-Man', 0:'Batman', 13:Superman}
>>> print(superheroes[7])
Spider-Man
>>> print(superheroes[0])
Batman
When we use “7” as the key, we are not trying to get the value at the index 7, We are trying to get the value with the key 7 and that is “Spider-Man” as expected.
We can also, of course, manipulate dictionaries i.e. change them however you like. We can replace Sushi with ‘Ramen’ or we can even add a new key (a new country, in this case!), Python provides all the necessary tools to do it and that is what we will be looking into next!
Assigning and Manipulating dictionary items
Manipulating dictionary items like adding, removing, and editing elements is actually pretty simple and straightforward in Python. Let me show you how to use our delicious dictionary ‘Dishes’ that we defined earlier.
Let me start by adding one more dish to our palette, Kimchi from Korea!
>>> Dishes['Korea'] = 'Kimchi'
>>> print(Dishes)
{'Japan': Sushi, 'China': 'Chinese Noodles', 'India': 'Roti', 'Turkey': 'Baklava', 'Korea': 'Kimchi'}
The syntax to assign values in dictionaries is as follows:
dict_name[key_name] = value_name
And voila! It’s as simple as that.
We can also use this same syntax to edit our current items by overwriting them.
A Challenge for you!
I’ve included mini-challenges here and there that will help you practice and implement what you are learning.
Challenge#1
I think Japan offers one more exquisite dish that I can never stop having enough of, Ramen! Since one key can have multiple values, I wish to add this to my dictionary whilst keeping my previous element as well, Sushi.
I also wish to swap ‘Roti’ for ‘Biryani’ for the key ‘India’
The following is the code to do what I want
>>> Dishes["Japan"] = ["Sushi","Ramen"]
>>> Dishes["India"] = "Roti"
>>> print(Dishes)
Before looking at the output, I want you to try and predict the output of the above code in your head. These thinking exercises will condition your brain to think like a programmer!
Ready? Alright here is the output!
Output of the code
{'Japan': ['Sushi', 'Ramen'], 'China': 'Chinese Noodles', 'India': 'Roti', 'Turkey': 'Baklava', 'Korea': 'Kimchi'}
Since values can be anything, using a list as a value allows us to store multiple values for the same key!
And that is how you assign and change your dictionary as you like. Now you know how to define, access, assign, and edit values for dictionaries. But wait, there is more!
When working with dictionaries, there are some tricks you should know that you can apply on dictionaries. These “tricks” or “spells” will do a lot of hard work to make your life easier. For example, if you wish to know how many items are in a given dictionary, you do not have to print it and sit and count each and every item instead you can simply use the built-in len() function as we will shortly see!
The following is a list of some of the common and handy tricks applied to dictionaries in python.
Dictionary: Tips and Tricks
The “len()” function
As the name suggests, it returns the length or the number of the key-value pairs in a dictionary.
Syntax:
len(dict_name)
For example, let’s say we have a dictionary of movies and their genres:
movies = {"Toy Story" : ["Animation","Adventure","Comedy"],
"The Godfather" : "Crime",
"Black Adam" : ["Fiction","Action"],
"Enola Holmes" : "Crime"
}
On running the len() function we get the following output
>>> print(len(movies))
4
This is because we have 4 movies inside the movies dictionary!
This is also shown in the following pic
The “in” keyword
The “in” keyword allows us to check whether a key exists inside a dictionary or not
For example, to check if we have dishes from Italy in our ‘Dishes’ dictionary, we can use the ‘in’ keyword as follows
if 'Italy' in Dishes:
print("The item Italy exists in the dictionary Dishes")
else:
print("The item Italy does not exist in the dictionary Dishes")
Output:
The item Italy does not exist in the dictionary Dishes
The syntax for using the “in” keyword can be given as
key in dict_name
This “in” keyword is a very useful one and we have an entire article dedicated to it, I suggest giving that one a read if the above example does not make complete sense to you!
There is another keyword called “not in” which does the exact opposite of the “in” keyword. The “not in” keyword is also explained in the article linked previously.
To table below summarizes the use of the len() function, the “in” keyword, and the “not in” keyword using the following example
dict1 = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
Example Code | Comments |
---|---|
>>> len(dict1) 3 | The in-built function len() is used to get the number of items in a given dictionary |
>>> if ‘b’ in dict1: … print(“b is a key in dict1”) b is a key in dict1 | Check if the specified key is present in the given dictionary using the “in” operator |
>>> if ‘d’ not in dict1: … print(“The key ‘d’ is not present in dict1”) The key ‘d’ is not present in dict1 | Check if the specified key is absent in the given dictionary using the “not in” operator |
Next, let us take a look at some of the methods that come with the dictionary class and see how we can employ those in our code to make our lives easier!
The get() method
Let us take our Dishes dictionary again
>>> Dishes = {'China': 'Chinese Noodles', 'India': 'Roti', 'Turkey': 'Baklava', 'Korea': 'Kimchi'}
If we wish to get the Turkish items from ‘Dishes’, we do it as follows:
>>> print(Dishes['Turkey'])
Baklava
Now if we wish to get the Dishes of Italy and we use the above syntax with square brackets, we will run into an exception as there is no Italy in our dictionary yet.
>>> print(Dishes['Italy'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Italy'
When writing professional code, exceptions like this need to be avoided as this will crash our programs. To do that python gives us the get() method. We can use it as follows.
>>> print(Dishes.get('Turkey'))
Baklava
>>> print(Dishes.get('Italy', "This country's cuisine is not available"))
This country's cuisine is not available
The get method takes in 2 arguments
- The key
- Default value (optional)
As you can see
- In the first case with Turkey, the key exists and the value is returned
- In the 2nd case, the key does not exist in the dictionary, and python gives out the default value (argument-2 of get() method) instead. I guess we won’t be seeing any Pasta today!
Thus we can save our code from an embarrassing crash and we can simply get a default value back.
Even if no default value is given to the get() method, there will not be any crash, and “None” will be returned as follows.
>>> print(Dishes.get('Italy'))
None
Hence the syntax for using the get() method is
dict_name.get(key_name)
#or
dict_name.get(key_name, default_value)
The keys() method
As you might have guessed, this method returns all the keys of a dictionary. This can be very helpful if you need to get a collection of only the keys of a dictionary
The syntax for using the keys() method is as follows
dict_name.keys()
Do have a look at the following example to understand better
The values() method
On the other hand, when you need to get the values from a dictionary, you can use the values method.
The syntax for using the values() method is
dict_name.values()
The following will help you understand better
The items() method
The items method is pretty much a combination of the keys() and the values() method. It returns the items of the specified dictionary as a sequence of key-value tuples.
The syntax to use items() is as follows:
dict_name.items()
Let us get all the items from the ‘Dishes’ dictionary:
>>> print(Dishes.items())
dict_items([('Japan', [Sushi, 'Ramen']), ('China', 'Chinese Noodles'), ('India', 'Roti'), ('Turkey', 'Baklava'), ('Korea', 'Kimchi')])
The popitem() method:
The popitem() method removes the last key-value pair from the dictionary and returns that.
Its syntax is
dict_name.popitem()
The last item we entered in the ‘Dishes’ dictionary was ‘Korea’, let us see if it works:
>>> last_item = Dishes.popitem()
>>> print(last_item)
('Korea', 'Kimchi')
>>> print(Dishes)
{'Japan': [Sushi, 'Ramen'], 'China': 'Chinese Noodles', 'India': 'Roti', 'Turkey': 'Baklava'}
It does! We got the ‘Korea’ and ‘Kimchi’ pair as expected. We can also see that this pair has been removed from the dictionary.
Advanced: What does “pop” mean?
The word “pop” comes from the sound made by the cork as you open a bottle like the one in the pic above.
I assume you have played the game of “Jenga”. If you are sliding a block “in”, we call that “pushing” and whenever you take a block “out” we call that “popping”.
But how does that relate to python dictionaries? Similar to the blocks of wood, the items in the list are stored blocks of memory locations. Hence we use the word “pop” to refer to a situation where we take items out of those memory locations!
Remember
Pop means remove and return!
The pop() method
If we wish to remove a specific item (as opposed to the last item added) and return the value alone (instead of both key and value) we can use the pop() method.
The pop() method removes the key-value pair and returns the value associated with the given key
>>> item_popped = Dishes.pop('Turkey')
>>> print(item_popped)
'Baklava'
>>> print(Dishes)
{'Japan': [Sushi, 'Ramen'], 'China': 'Chinese Noodles', 'India': 'Roti'}
The syntax is
dict_name.pop(key)
# or
dict.pop(key, default_value)
As you can see there in an optional 2nd argument called “default value” just like the get() function.
But, unlike the get() function, if the default value is not passed and the key is not present, the function raises a KeyError exception.
Challenge#2
Let’s apply the pop() method in the ‘Dishes’ dictionary:
>>> print(Dishes.pop('India'))
Roti
Let us try another pop!
>>> print(Dishes.pop('India','This country does not exist in the dictionary'))
Now try to guess what the output will be this time!
Ready? okay, let us look at the output!
OUTPUT
This country does not exist in the dictionary
As you might have guessed, the first pop removed the key-value pair ‘India’ and returned the value ‘Roti’, and printed it as instructed.
Since the pair is removed, the second pop method returns the default value which is then printed.
The clear() method
As the name suggests, it clears the dictionary (empties it)
The syntax is:
dict_name.clear()
If we were to pass the following statement:
>>> Dishes.clear()
Our beloved dictionary would be emptied, I do not want to do that now, I suggest you do it yourself on your computers!
The update() method
Let us take an example.
#the dictionary contains the ocean names and their avg. depth in meters
>>> ocean_depth1 = {'Pacific Ocean': 11022, 'Indian Ocean':7258}
>>> ocean_depth2 = {'Atlantic Ocean':8486}
Here we have 2 dictionaries, the 1st dict has 2 items, and the 2nd dict and 1 item. Now if I want to get all 3 into a single dict I can use the update method as follows.
>>> ocean_depth1.update(ocean_depth2)
>>> print(ocean_depth1)
{'Pacific Ocean': 11022, 'Indian Ocean': 7258, 'Atlantic Ocean': 8486}
The update() here method merges the 1st dictionary with the 2nd dictionary. All the key-value pairs in both dictionaries are added to the first dictionary. This means only the first dictionary is updated. If we print the 2nd one we still get what we had in the beginning.
>>> print(ocean_depth2)
{'Atlantic Ocean':3646}
- If a key is already present in the first dictionary, its value is updated by the value associated with the key in the second dictionary.
- If a key is not present in the first dictionary but is present in the second one, it is added to the first dictionary
The syntax to use is
dict1.update(dict2)
Challenge#3
Create a dictionary that has all the keys and values we removed and edited from our dictionary ‘Dishes’ until our journey here.
Use the update method to join the ‘Dishes’ dictionary with this new dictionary that you have just created to finally get the very first unchanged ‘Dishes’ we had at the beginning
All the methods so far are presented in the pic below. You can save this pic for easy reference later if you want to!
Summary
- In this article, we saw how the Dictionary in Python is a collection of key-value, used to store data values like a map.
- We also saw we can define dictionaries by having a list of key-value pairs that are joined by a colon, while each pair is separated by a comma.
- We went on to assign values to a dictionary, if the key-value already exists, the value gets updated, otherwise, a new key with the value is added to the Dictionary.
- We then went through a list of important methods that can be used in dictionaries. You can save the below cheat sheet to refer to it easily later.
And that’s the end of it folks! Congrats on making it this far, not many people have the perseverance to read through the entire thing!
All the best in your Python journey ahead, and as always, you can come to Embeddedinventor for more explanations and articles!
Here are some related articles you might find interesting!
Related Articles
Python Lists: Everything You Need To Know
Credits: Thanks to Namazi Jamal for his contributions to the creation of this article.