Nested dictionary in Python [Practical Examples]

 

Introduction to the nested dictionary in Python

A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,). A colon (:) separates each key from its value. You can learn more about Python dictionaries from the article python dictionary

In this tutorial, we will learn about the nested dictionary in Python. We will learn how to create a nested dictionary in Python by solving examples. We will also discuss how we can add or remove elements from the nested dictionary in Python. At the same time, we will also cover how we can remove items and merge two nested dictionaries. Moreover, we will see how we can iterate through nested dictionaries as well. In a nutshell, this tutorial is going to have all the necessary information and examples that you need to know in order to start working with nested dictionaries.

Advertisement

 

Getting started with the nested dictionary in Python

A nested dictionary in Python  is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. For example, the following is an example of nested dictionary:

nested_dict = { 'key1': {'nested_key1': 'value1'},
                'key2': {'nested_key2': 'value2'}}

Notice that the value of the key1 is another dictionary and the value of key2 is also another dictionary. Such a dictionary that contains another dictionary is called a nested dictionary in Python.

Creating a simple and nested dictionary in Python

Now let us take a practical example and create a simple and nested dictionary using the Python programming language. See the example below, where we first created a simple dictionary and then prints it.

# defining python dictionary
myDict = {"student1": "Bashir" , "student2": "Alam", "student3" : "erlan" }
# printing the dict
print(myDict)

Output:

{'student1': 'Bashir', 'student2': 'Alam', 'student3': 'erlan'}

The curly brackets are used to define the dictionary and as you can see in the above example, the semi-colon (:) is used to separate a key from its values. Now, let us create a nested dictionary and print it. See the example below:

# defining python dictionary
myDict = {"student1": {"age": 23, "class": 12} , "student2": {"age": 22, "class": 15}}
# printing the dict
print(myDict)

Output:

Advertisement
{'student1': {'age': 23, 'class': 12}, 'student2': {'age': 22, 'class': 15}}

So a nested dictionary is a dictionary that contains a dictionary as shown in the above example.

 

The dict() constructor in Python

Python dict() method is a constructor which creates a dictionary. If no argument is passed, it creates an empty dictionary. If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object. And if keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. In this section, we will create a nested dictionary using dict() method.

 

Example-1:

Now let us take an example and see how we can use the dict() method to create a python nested dictionary. See the example below:

# using dict method to create nested dictionary in Python
myDict = dict(student1 = {'name': 'Bashir', 'age': 23},
         student2 = {'name': 'alam', 'age': 22},
         student3 = {'name': 'Sam', 'age': 20})
# printing 
print(myDict)

Output:

{'student1': {'name': 'Bashir', 'age': 23}, 'student2': {'name': 'alam', 'age': 22}, 'student3': {'name': 'Sam', 'age': 20}}

In the above example, we have simply passed key: value pairs to the dict() method and it creates a dictionary.

 

Example-2:

Now let us take another example and see how we can create a python nested dictionary using dict() method, but this time we will use zip() method as well. See the example below:

# creating list of keys
Keys = ['student1','student2','student3']
# list of values
values = [{'name': 'Bashir', 'age': 22},
           {'name': 'Kim', 'age': 20},
           {'name': 'erlan', 'age': 32}]
# using zip and dict methd to create nested dictionary in Python
myDict = dict(zip(Keys, values))
# printing the dict
print(myDict)

Output:

{'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kim', 'age': 20}, 'student3': {'name': 'erlan', 'age': 32}}

So the zip function combines the two lists together and passed them to the dict() method as key: value pairs.

Advertisement

Accessing the elements of nested dictionary in Python

We can get access to the elements of a nested dictionary in a similar way as we access the elements of a simple dictionary. But we have to specify the key of the nested dictionary as well. Now let us take an example and see how we can access the elements of a nested dictionary in Python.

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12},
     'student3': {'name': 'Sameer', 'age': 23}}
# accessing the elements of nested dictionary in Python
print(myDict['student1'])

Output:

{'name': 'Bashir', 'age': 22}

Notice that we get the whole dictionary as output because it is considered to be the value of key student1. Let say, we only want to get access to the age of student1. We can do it in the following way.

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12},
     'student3': {'name': 'Sameer', 'age': 23}}
# accessing the elements of nested dictionary in Python
print(myDict['student1']['age'])

Output:

22

Notice that we defined the key of the nested dictionary to get access to individual values inside the nested dictionary.

 

Changing the elements of nested dictionary in Python

Changing the elements of the nested dictionary is very simple. All we need to do is to get access to the element and then specify the new value. See the example below where we changed the name of the student1. 

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12},
     'student3': {'name': 'Sameer', 'age': 23}}
# printing
print("The dictionary before changing:", myDict)
# changing the element of nested dictionary
myDict['student1']['name'] = 'GoLinuxCloud'
# printing
print("The dictionary after changing :", myDict)

Output:

The dictionary before changing: {'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}, 'student3': {'name': 'Sameer', 'age': 23}}
The dictionary after changing : {'student1': {'name': 'GoLinuxCloud', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}, 'student3': {'name': 'Sameer', 'age': 23}}

Notice that we have successfully changed the name of the student1 by getting access to its name.

 

Updating nested dictionary in Python

Updating nested dictionary items is again very easy. Just refer to the item by its key and assign a value. If the key is already present in the dictionary, its value is replaced by the new one. See the example where we update our dictionary with a new key and values.

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12}}
# print
print("Before updating:", myDict)
# updating dictionary
myDict['student4'] =  {'name': 'Sameer', 'age': 23}
# print
print("After updating :", myDict)

Output:

Before updating: {'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}}
After updating : {'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}, 'student4': {'name': 'Sameer', 'age': 23}}

Notice that we updated the dictionary by defining a new key and its values. If we will try to update with a key that already exists in the dictionary, then its values will be changed by the new values. See the example below:

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12}}
# print
print("Before updating:", myDict)
# updating dictionary
myDict['student2'] =  {'name': 'Sameer', 'age': 23}
# print
print("After updating :", myDict)

Output:

Before updating: {'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}}
After updating : {'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Sameer', 'age': 23}}

In the above example, notice that the values of student2 have been updated to new values.

 

Merging two nested dictionaries in Python

We can use an update method to merge the keys and values of nested dictionaries into one another. But we have to keep in mind that this method blindly overwrites values of the same key if there are any: See the example below:

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12}}
myDict1 = {'student3':{'name':'Nat', 'age': 13}}
# merging two dictionaries in Python
myDict.update(myDict1)
# printing
print(myDict)

Output:

{'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}, 'student3': {'name': 'Nat', 'age': 13}}

Notice that we successfully merge the two nested dictionaries using the update method.

 

Removing elements from the nested dictionary in Python

There can be several ways to remove elements from nested dictionaries in Python. Here we will discuss only two method which are commonly used among programmers. See the examples below:

Example-1: Using the pop method

If we know the name of the key that we want to remove, then we can use the pop method and pass the key as an argument, and this method will remove that specified key from our dictionary. See the example below:

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12},
     'student3':{'name':'Nat', 'age': 13}}
# removing elements from nested dictionary using pop method
myDict.pop('student3')
# printing
print(myDict)

Output:

{'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}}

Notice that we have removed the information about student3 by using the pop method and passing student3 as an argument.

 

Example-2:Using the del keyword

Another method to remove elements from the nested dictionary in python is to use the keyword del. The syntax is very simple. See the example below, which uses the keyword del to remove elements from the nested dictionary.

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12},
     'student3':{'name':'Nat', 'age': 13}}
# removing elements from nested dictionary using pop method
del myDict['student3']
# printing
print(myDict)

Output:

{'student1': {'name': 'Bashir', 'age': 22}, 'student2': {'name': 'Kane', 'age': 12}}

The del keyword is also used to remove elements from a dictionary as shown in the above example.

 

Iterating through the nested dictionary in Python

Python for loop and while loops are mostly used to iterate through an iterable object. You can learn more about the while and for loop from the article python while loop and python for loopIn this section, we will use python for loop to iterate through the nested dictionary. See the example below:

# defining nested dictionary in python
myDict = {'student1': {'name': 'Bashir', 'age': 22},
     'student2': {'name': 'Kane', 'age': 12},
     'student3':{'name':'Nat', 'age': 13}}
# for loop to iterate through nested dictionary
for i, y in myDict.items():
    # printing keys of outer dictionary
    print("the info about ",i)
    # nested for loop
    for nested_value in y:
        # printing nested keys and values
        print(nested_value)
        print(y[nested_value])

Output:

the info about student1
name
Bashir
age
22
the info about student2
name
Kane
age
12
the info about student3
name
Nat
age
13

Notice that we have used nested for loop to iterate through the given dictionary because it was also nested.

 

Summary

A nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. In this tutorial, we learned about Python nested dictionaries. We covered how to create nested dictionaries through various methods. We also discuss how to remove or add a new element to the nested dictionary. At the same time, we also covered how we merge two nested dictionaries together. Moreover, used for loop to iterate through elements of nested dictionary in Python. To summarize, this tutorial contains all the necessary information and examples that you need to know in order to start working with Python nested dictionary.

 

Further Reading

Python dictionary
Python nested dictionary
More about Python dictionary

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment