What is Nested Dictionary in Python?

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

You must be familiar with dictionaries in Python. However, before moving ahead with the agenda of our article, let us get a quick recap of the dictionary in Python.

Dictionary in Python is one of the most popular data structures. Dictionaries are used to store data in a "key-value" pair format. The keys are always unique within a dictionary. The values of the Python dictionary may or may not be unique. We can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value.

introduction to Nested Dictionary in Python

So, what are Nested Dictionaries?

In Python, a nested dictionary is a dictionary inside a dictionary. Basically, it is a collection of dictionaries kept inside a single dictionary.

Nested dictionaries are one of the ways to represent and store structured information (similar to some ‘records’ in other languages).

nested dictionary inside a dictionary

Below given is a simple example of a nested dictionary.

We shall understand the above code in depth going further.

Creating a Nested Dictionary

Creating a nested dictionary is very similar to how we create any other normal dictionary. There is a very basic difference that, in the nested dictionary, the value can also be a dictionary.

Let us understand this clearly through an example. Suppose, we have kept the records of 3 students in a dictionary. Say, an individual student has the following properties: Name, Class, and Roll No.

Creating a Nested Dictionary

We can represent this very clearly through a nested dictionary.

Explanation: In the above example, we have created a dictionary named "school". This is a nested dictionary which has the student index as the key and the student's properties like name, roll and class are the values of the keys. But here, please note that every key is mapped to a value which itself is a dictionary. In simple words, the values in this dictionary are the dictionary itself. So, this is how we create a nested dictionary.

Let us also learn about an important way of creating nested dictionaries.

The dict() Constructor

There is a "type constructor" called dict() in Python, that can be used to create python dictionaries from keyword arguments or any kind of key-value pairs. It can even create a dictionary from another dictionary and keyword arguments.

These terms might not be making any sense to you, hence let us understand how is the dict() constructor used to create a nested dictionary through easy examples.

1. Keyword Arguments to Nested Dictionary

To create a nested dictionary, we can simply pass our dictionary key : value pair as keyword arguments to the dict() constructor. For example, look at the code below --

Output:

In the above example, please note that we have enclosed our dictionary into round brackets '()' and passed it to the dict() constructor --

As a result, the dict() constructor transformed the above keyword arguments into nested dictionary.

Click here to read about Constructor in Python

2. Using zip() Method in Python

The zip() function takes some iterables (can be zero or more), sums them up in a tuple, and return them. We can use zip to combine separate lists of keys and values. We can also pass the list of keys and values to the zip() function in Python dynamically at runtime.

Output:

3. Using Python Dictionary fromkeys() Method

The fromkeys() method in python dictionary creates a new dictionary with the default value for all specified keys. In case we do not specify any default value then, all the keys are set to None.

Code:

Output:

We can use the dict.fromkeys() method to create a nested dictionary with some default values. For example, consider the given code below --

Code:

Output:

Explanation: As we explained above, the fromkeys() created a dictionary based on the keys and default the values we passed to it.

Access Nested Dictionary Items

We can access the items of a dictionary by specifying the key of the dictionary and key of the nested dictionary into square brackets. For example, consider the below code:

Code:

Output:

Exception: If we try to access any key-value pair that doesn't exist in our dictionary, we will get a keyerror.

Code:

Output:

However, we can prevent our codes to fall into any key error. This can be done using the special dictionary get() method. The get() method returns the value for the key if the key is in the dictionary, otherwise, it returns None. Hence, we never get the keyError if we use this method.

Code:

Output:

Deleting Dictionaries from a Nested Dictionary

Deleting a dictionary from a nested dictionary is a straightforward operation, for which, we can use python's del keyword. Another way to delete a dictionary is, by using the pop() method in python.

1. Using the pop() Method

pop() is generally used when we want the value of the dictionary after deleting it. So, pop() returns a value. For example, look at the code below:

Code:

Output:

2. Using del Keyword

Another way to delete a dictionary is by using del keyword in Python. This is generally used when we do not want the value which is deleted. For example, look at the code below:

Code:

Output:

Add or Update Element to a Nested Dictionary

We can add or update the elements of a nested dictionary very simply. However, there is a difference when we are trying to add a new key to our dictionary or update any existing key. The difference is --

  • If the key is already present in the dictionary, value gets updated.
  • If the key is not present in the dictionary, a new key: value pair is added to the dictionary.

Let us understand these in-depth below through code. If we add a key-value pair to a nested dictionary, with a key that is already present into the original nested dictionary, then the old value gets updated. For example, look at the code below:

Code:

Output:

Explanation: In the above example, we try to add an element to the dictionary, but please note that the key already exists in our dictionary. Since the key is already present in the dictionary, its value is replaced by the new one.

Let us now see by adding a new element to our dictionary.

Code:

Output:

In this example, we have used a new key so it directly gets added to our nested dictionary. And, hence the dictionary has a new element added. So this is a major difference, if our key already exists in our dictionary then our dictionary gets updated, otherwise, a new key-value pair is added to the dictionary.

Delete Elements from a Nested Dictionary

We have already seen how to delete a dictionary item from a nested dictionary. Here we will learn how can we remove a single element or value from a nested dictionary.

Removing value from a nested dictionary is very similar to removing a dictionary item itself. There are mainly 2 ways(precisely 3). Let us learn each of them.

Using del Keyword in Python

We can use the del keyword to delete an element from our nested dictionary. However, del does not return anything hence we cannot retrieve the element which we have deleted using it. Let us see an example to demonstrate its usage.

Code:

Output:

Explanation: In the above example, we used the del keyword to delete the value from the dictionary. We fetched the value of the dictionary using the key. We can also use indexing to delete elements at any particular index.

Using pop() Method

We can use the pop() method to delete an element from our nested dictionary. Unlike the del keyword, pop() returns the value whenever it deletes any item. So, it is recommended to use the pop() method whenever we want to fetch the value of the element we deleted. Below given is an example of using pop to delete elements.

Code:

Output:

Explanation: As explained above, we fetch the dictionary elements values to be deleted using the key of the nested dictionary. Later, we store the values of the elements that are popped using pop().

Iterate through Each Element in a Nested Dictionary

In normal dictionaries, we can iterate over the dictionary using dict.items(). But, this is not the case with nested dictionaries. Here, we can have dictionaries within dictionaries and hence we have to go to one more level for iterating through their values.

We can iterate in a nested dictionary using the nested for-loop. Let us look at our code to understand it better.

Code:

Output:

Explanation: In the above example, we first iterate over the dictionary items, which in turn gives us the key value pair keykey, valval . Now, the resulting value valval is another dictionary. Hence, we iterate over val.items() to get nestedKeynestedKey and nestedValnestedVal. This code will work fine if we have only one level of nested dictionary. For n-levels of the nested dictionary, this is not the appropriate way.

In this article, we learned how can we iterate over a nested dictionary which is 1 level nested (only 1 dictionary inside a dictionary). However, there are cases where we might have n-levels of nested dictionaries. For them, the simplest way to iterate is through recursively calling it's each level of nesting. Please note, that the n-level nested dictionary is not under the scope of this article.

Merge Two Nested Dictionaries

Two nested dictionaries can be merged using the update() method in Python.

update method():

The update() method updates the dictionary with the key: value pairs from the element.

  • If the key is already present in the dictionary, the value gets updated.
  • If the key is not present in the dictionary, a new key: value pair is added to the dictionary.

Syntax:

Let us see the code below to update any dictionary.

Code:

Output:

Explanation: In the above example, we update the my_dict1 dictionary with my_dict2 dictionary. While doing so, whichever key is already present in my_dict1 gets overwritten by key of my_dict2. And, if the key is not present, then a new key gets added. For example, BB key gets updated in the my_dict1 dictionary. And new key DD is added in my_dict1, because it was not already present.

Important conclusions:

  1. update() method blindly overwrites values of the same key if there’s a clash(or equal key in 2 dictionaries).
  2. update() method updates the dictionary directly, it does not return anything.

This article included all the major points you need to know to get a brief idea about nested dictionaries in Python. You may also refer to the below scaler articles to know more about Dictionary in Python. Also, the prerequisite to this article is dictionary in Python.

Conclusion

In this article, we learnt about nested dictionaries in Python. Let us recap what we learned throughout.

  1. A dictionary can contain another dictionary, which in turn can contain dictionaries themselves, which are nested dictionary in python.
  2. We can create a nested dictionary in python using the dict() Constructor
  3. We can access a nested dictionary in python using either the index or the keys of the dictionary.
  4. We can add or update any item by referring to its key and assigning a value. If the key is already present in the dictionary, its value is replaced by the new one.
  5. Removing dictionary items can be performed using del and pop() method in Python.
  6. Iterating of nested dictionary in python can be performed by using a nested for loop in python.
  7. Merging of nested dictionary in python can be done using update().