In this article we will focus on a complete walk through of a Python dictionary data structure.

Table of contents


What is a Python dictionary

A Python dictionary is a data structure for storing groups of objects. It consists of a mapping of key-value pairs, where each key is associated with a value. It can contain data with the same or different data types, is unordered, and is mutable.


How to create a Python dictionary

Empty dictionary

To initialize an empty dictionary in Python we can simple run the code below and print its content:


empty_dict = {}

print(empty_dict)

You should get:

{}

Dictionary with values

When we want to create a dictionary with some values that we want to populate, we add the values as a sequence of comma-separated key-value pairs. For example, let’s say we want to create a dictionary with countries as keys and their populations as values:


countries = {
    "China": 1439323776,
    "India": 1380004385,
    "USA": 331002651,
    "Indonesia": 273523615,
    "Pakistan": 220892340,
    "Brazil": 212559417
}

print(countries)

You should get:

{'China': 1439323776, 'India': 1380004385, 'USA': 331002651, 'Indonesia': 273523615, 'Pakistan': 220892340, 'Brazil': 212559417}

How to access values from a Python dictionary

In order to access values stored in a Python dictionary, we should use they key associated with the value. For example, let’s say we ant to get the population of USA from the above countries dictionary. We know that they key of the population value is “USA”, and we use it to access the population value:


usa_population = countries["USA"]

print(usa_population)

You should get:

331002651

Note: unlike Python list, you can’t access values from the dictionary using indices. The only way to access the values is by searching a key that is present in the dictionary.


How to add elements to a Python dictionary

In this section we continue working with the countries dictionary and discuss ways of adding elements to a Python dictionary.

Add a single element

Let’s say we want to add another country with its population to our countries dictionary. For example, we want to add Japan’s population of 126,476,461. We can easily do it by adding it as an additional key-value pair to the dictionary:


countries["Japan"] = 126476461

print(countries)

You should get:

{'China': 1439323776, 'India': 1380004385, 'USA': 331002651, 'Indonesia': 273523615, 'Pakistan': 220892340, 'Brazil': 212559417, 'Japan': 126476461}

And you can see that we have successfully added a new element to the dictionary.


Add multiple elements

Now, what if we want to add more than one country? Let’s say we now want to add two more countries with their populations to our dictionary. For example, Russia and Mexico with populations of 145,934,462 and 128,932,753 respectively.

Will the same syntax work? Well, not really. We will need to use the .update() method of a Python dictionary data structure. What it allows to do is to add multiple comma-separated key-value pairs to the dictionary.

The logic is to create a new dictionary (new_countries) from the new key-value pairs and then merge it into the countries dictionary:


new_countries = {
    "Russia": 145934462,
    "Mexico": 128932753
}
countries.update(new_countries)

print(countries)

You should get:

{'China': 1439323776, 'India': 1380004385, 'USA': 331002651, 'Indonesia': 273523615, 'Pakistan': 220892340, 'Brazil': 212559417, 'Japan': 126476461, 'Russia': 145934462, 'Mexico': 128932753}

And you can see that we have successfully added new elements to the dictionary.


How to remove elements from a Python dictionary

In this section we continue working with the countries dictionary and discuss ways of removing elements from a Python dictionary.

Remove a single element

Let’s say we need to make some changes and remove a key-value pair for China and its population from a dictionary. We can easily remove it using the .pop() method:


countries.pop("China")

print(countries)

You should get:

{'India': 1380004385, 'USA': 331002651, 'Indonesia': 273523615, 'Pakistan': 220892340, 'Brazil': 212559417, 'Japan': 126476461, 'Russia': 145934462, 'Mexico': 128932753}

And you can see that we have successfully removed an element from the dictionary.


Remove multiple elements

The next step is to explore how to remove multiple elements from a Python dictionary. Let’s say we want to remove Japan and Mexico and their respective populations from the countries dictionary.

We know that .pop() method allows to remove a single element per function call, which gives us an idea that if we iterate over a list with keys we want to remove, we can successfully call .pop() for each entry:


to_remove = ["Japan", "Mexico"]
             
for key in to_remove:
    countries.pop(key)

print(countries)

You should get:

{'India': 1380004385, 'USA': 331002651, 'Indonesia': 273523615, 'Pakistan': 220892340, 'Brazil': 212559417, 'Russia': 145934462}

And you can see that we have successfully removed the elements from the dictionary.


How to change elements in a Python dictionary

Another functionality to cover is changing elements in a Python dictionary. You will see in the sections below that the functionality of changing elements is identical to functionality of adding elements.

Why is that? It happens because when we try to add new elements to the dictionary, Python looks for that specific key we are trying to add and if the key exists in the dictionary, it overrides the data; but if the key doesn’t exist, it adds a new key-value pair to the dictionary.

Change a single element

Let’s say we want to update the value of Brazil’s population to 212560000 in the countries dictionary:


countries["Brazil"] = 212560000

print(countries)

You should get:

{'India': 1380004385, 'USA': 331002651, 'Indonesia': 273523615, 'Pakistan': 220892340, 'Brazil': 212560000, 'Russia': 145934462}

Change multiple elements

Now, let’s say we want to update the values of Indonesia and Pakistan populations to 273530000 and 220900000 in the countries dictionary respectively.

The logic is to create a new dictionary (update_countries) from the new key-value pairs and then update the existing key-value pairs in the countries dictionary:


update_countries = {
    "Indonesia": 273530000,
    "Pakistan": 220900000
}

countries.update(update_countries)

print(countries)

And you should get:

{'India': 1380004385, 'USA': 331002651, 'Indonesia': 273530000, 'Pakistan': 220900000, 'Brazil': 212560000, 'Russia': 145934462}

How to iterate over a Python dictionary

In this section we will focus on different ways of iterating over a Python dictionary.

Iterate over dictionary keys

Let’s say we want to iterate over the keys of the countries dictionary and print each key (in our case each country) on a separate line.

We will simply use a for loop together with .keys() dictionary method:


for country in countries.keys():
    print(country)

And you should get:

India
USA
Indonesia
Pakistan
Brazil
Russia

Iterate over dictionary values

Another use case can be that we want to find the sum of all countries’ populations stored in the countries dictionary.

As you can imagine, we will need to use a for loop again, and also now we will use the .values() dictionary method:


sum_populations = 0

for population in countries.values():
    sum_populations += population
    
print(sum_populations)

And you should get:

2563931498

Iterate over dictionary items

And item of a Python dictionary is its key-value pair. This allows us to do the iteration over keys and values together.

How can we use it? Let’s say you want to find the country with the largest population from the countries dictionary. Iterating over each item of the dictionary allows us to keep track of both keys and values together:


max_population = float('-inf')
max_country = ''

for country, population in countries.items():
    if population > max_population:
        max_population = population
        max_country = country
        
print(max_country, max_population)

And you should get:

India 1380004385

Nested dictionaries in Python

A nested dictionary is a dictionary that consists of other dictionaries.

You can create nested dictionaries in a similar way of creating dictionaries.

For example, let’s say we want to create a dictionary that will have information about each country’s capital as well as its population:


countries_info = {
    "China": {"capital": "Beijing", "population": 1439323776},
    "India": {"capital": "New Delhi", "population": 1380004385},
    "USA": {"capital": "Washington, D.C.", "population": 331002651},
    "Indonesia": {"capital": "Jakarta", "population": 273523615},
    "Pakistan": {"capital": "Islamabad", "population": 220892340},
    "Brazil": {"capital": "Brasilia", "population": 212559417}
}

print(countries_info)

And you should get:

{'China': {'capital': 'Beijing', 'population': 1439323776}, 'India': {'capital': 'New Delhi', 'population': 1380004385}, 'USA': {'capital': 'Washington, D.C.', 'population': 331002651}, 'Indonesia': {'capital': 'Jakarta', 'population': 273523615}, 'Pakistan': {'capital': 'Islamabad', 'population': 220892340}, 'Brazil': {'capital': 'Brasilia', 'population': 212559417}}

Conclusion

This article is an introductory walkthrough on Python dictionary and its methods which are important to learn as they are used in many areas of programming and in machine learning.

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Data Structures articles.