How to Use Python Dictionaries: The Vertabelo Guide
Wondering how to get the most out of Python dictionaries? In this comprehensive guide, we’ll cover all you need to know to effectively use dictionaries in your studies and in real-world projects.
What Is a Python Dictionary?
A Python dictionary is yet another very useful and important data type. Basically, Python dictionaries are an unordered collection of data values. However, in contrast to other data types, a dictionary’s elements are key-value pairs instead of single data values. Each of these pairs maps the key to the associated value. For example, in the dictionary below, we map European countries (the keys) to their respective capital cities (the values).
Like Python lists, Python dictionaries:
- Are mutable and dynamic, meaning that you can add, delete, and change their elements.
- Can be nested, meaning that a dictionary can contain another dictionary.
In contrast to lists, which are accessed via indexing, dictionary elements are accessed via keys. Thus, it’s important that Python dictionary keys are unique and of an immutable data type (e.g. integers, strings, tuples). At the same time, dictionary values can be of any data type, including lists, tuples, and even other dictionaries.
How to Create and Access a Python Dictionary
If you want to create an empty Python dictionary, curly brackets are all you need.
If you are creating a Python dictionary with certain elements, you will need to enclose your key-value pairs in curly brackets. Use a colon (:) to separate a key from the corresponding value and a comma (,) to separate one pair from another key-value pair.
You can also use the built-in function dict()
to create a new dictionary in Python. Here is an example of creating a Python dictionary:
#Creating Python dictionaries empty = {} game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} gdp = dict({'indicator':'Nominal GDP', 1:'USA', 2:'China', 3:'Japan'}) print(empty) print(game_of_thrones) print(gdp)
{} {'name': 'Game of Thrones', 'genre': 'fantasy', 'country': 'USA', 'number of seasons': 8} {'indicator': 'Nominal GDP', 1: 'USA', 2: 'China', 3: 'Japan'}
As you can see in the above example, where we rank countries by their nominal GDP, it’s fine to have keys of different data types in one dictionary as long as 1) all the keys are unique, and 2) all keys are of immutable data types.
Accessing elements in Python dictionaries is also straightforward – just use the associated key. Basically, there are two ways to access a dictionary element:
- Enclosing a corresponding key in square brackets.
- Using the
get() method
. This approach is usually preferred, as it returns None instead ofKeyError
if the key is not found in the dictionary.
Let’s see how that works.
#Accessing elements of a dictionary with square brackets capitals = {'Belgium':'Brussels','France':'Paris', 'Germany':'Berlin', 'Italy':'Rome', 'Poland':'Warsaw'} print(capitals['Belgium']) print(capitals['Portugal'])
Brussels --------------------------------------------------------------------------- KeyError Traceback (most recent call last)in () 2 capitals = {'Belgium':'Brussels','France':'Paris', 'Germany':'Berlin', 'Italy':'Rome', 'Poland':'Warsaw'} 3 print(capitals['Belgium']) ----> 4 print(capitals['Portugal']) KeyError: 'Portugal
#Accessing elements of a dictionary with the (get) method capitals = {'Belgium':'Brussels','France':'Paris', 'Germany':'Berlin', 'Italy':'Rome', 'Poland':'Warsaw'} print(capitals.get('Belgium')) print(capitals.get('Portugal'))
Brussels None
As expected, using a key enclosed in square brackets works perfectly well when the corresponding key is present in the dictionary, but it returns an error if the key is missing. The get()
method works fine in both cases.
How to Edit Python Dictionaries
As we have already discussed, Python dictionaries are mutable and dynamic. Thus, you can update dictionary elements, add new elements, or delete existing ones.
To update a dictionary element, just assign a new value to this element by referring to it with the associated key.
#Updating dictionary game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':7} game_of_thrones['number of seasons'] = 8 print(game_of_thrones)
{'name': 'Game of Thrones', 'genre': 'fantasy', 'country': 'USA', 'number of seasons': 8}
Notice how we updated the number of seasons in the Game of Thrones series from “7” to “8” by simply assigning a new value to the corresponding key.
In Python, adding new entries to a dictionary is also quite easy. You just need to define a value for the new key. Look at the example below. By adding the corresponding key-value pair, we add the information that the Game of Thrones series was originally created in English.
#Adding elements game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} game_of_thrones['language'] = 'English' print(game_of_thrones)
{'name': 'Game of Thrones', 'genre': 'fantasy', 'country': 'USA', 'number of seasons': 8, 'language': 'English'}
Furthermore, you can update one Python dictionary with the elements of another dictionary by using the update()
method.
#Merging dictionaries game_of_thrones_1 = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} game_of_thrones_2 = {'name':'Game of Thrones', 'genre':'serial drama', 'composer':'Ramin Djawadi', 'year':2011} game_of_thrones_1.update(game_of_thrones_2) print(game_of_thrones_1)
{'name': 'Game of Thrones', 'genre': 'serial drama', 'country': 'USA', 'number of seasons': 8, 'composer': 'Ramin Djawadi', 'year': 2011}
As you can see from the example, we basically append one Python dictionary to another. However, note that if the same key-value pair is present in both dictionaries, it will not be duplicated (i.e. name – “Game of Thrones”). If the values for the same key are different, the updated dictionary will include the value from the second
dictionary (i.e. genre – “fantasy” will become genre – “serial drama”).
To remove certain elements of a dictionary, use the del
keyword and the key associated with the value you want to remove. See how we remove genre information in the example below:
#Removing elements game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8, 'language':'English'} print(game_of_thrones) del game_of_thrones['genre'] print(game_of_thrones)
{'name': 'Game of Thrones', 'country': 'USA', 'number of seasons': 8, 'language': 'English'}
If you want to delete the entire dictionary, you basically have two options: either deleting all elements of the dictionary or deleting the dictionary itself. To remove the elements of a dictionary, use the clear()
method. To remove the entire dictionary, use the del
keyword.
#Removing all elements game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} game_of_thrones.clear() print(game_of_thrones)
{}
#Deleting the entire dictionary game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} del game_of_thrones print(game_of_thrones)
--------------------------------------------------------------------------- NameError Traceback (most recent call last)in () 2 game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} 3 del game_of_thrones ----> 4 print(game_of_thrones) NameError: name 'game_of_thrones' is not defined
Note that if you remove all the elements of the dictionary, it is still available (but empty). However, when you choose to delete the entire dictionary with the del
keyword, that dictionary doesn’t exist anymore; you’ll get an error if you try to access it.
More Built-in Python Dictionary Methods
Finally, let’s go through some of Python’s other very useful built-in dictionary methods:
items()
returns a list of tuples with the key-value pairs.keys()
returns a list of all keys in the dictionary.values()
returns a list of all values in the dictionary.
game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} print('Items:', list(game_of_thrones.items())) print('Keys:',list(game_of_thrones.keys())) print('Values:',list(game_of_thrones.values()))
Items: [('name', 'Game of Thrones'), ('genre', 'fantasy'), ('country', 'USA'), ('number of seasons', 8)] Keys: ['name', 'genre', 'country', 'number of seasons'] Values: ['Game of Thrones', 'fantasy', 'USA', 8]
Technically, the above methods return view objects rather than lists. However, you can easily turn these objects into the lists with the list()
function.
pop()
removes a key from the dictionary and returns its value.popitem()
removes either a random key-value pair (in Python versions before 3.7) or the item that was last inserted into the dictionary (in later versions) and returns this item as a tuple.
game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} game_of_thrones.pop('country')
'USA'
game_of_thrones.popitem()
('number of seasons', 8)
print(game_of_thrones)
{'name': 'Game of Thrones', 'genre': 'fantasy'}
Note how we have removed two key-value pairs from our dictionary with the pop()
and popitem()
methods.
copy()
returns a shallow copy of the dictionary.
#Creating a copy of a dictionary empty = {} game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8} copy_game_of_thrones = game_of_thrones.copy() print('New copy;', copy_game_of_thrones)
game_of_thrones = {'name':'Game of Thrones', 'genre':'fantasy', 'country':'USA', 'number of seasons':8}
Practicing Python Dictionaries
Now that you know the basics of Python dictionaries, it’s time to practice!
Take Vertabelo Academy’s Python Basics: Part 2 course to learn how to use Python dictionaries efficiently. With dozens of interactive exercises, you’ll learn how to:
- Access, add and delete elements of a Python dictionary.
- Use the IN operator.
- Iterate over dictionaries with
keys()
,values()
, anditems()
. - Use dictionaries in functions.
Thanks for reading, and happy learning!