In this tutorial, we will discuss the concept of a Python nested dictionary i.e. a dictionary inside another dictionary. Also, we will learn how to create and access nested dictionaries and their elements in the Python programming language.
With the help of some examples, we will also modify the nested dictionary elements. A normal dictionary is a collection of key-value pairs , and all the keys and their corresponding values are stored in an unordered fashion. We use curly braces { } to define a dictionary.
Example:
What is a (Python) Nested Dictionary?
When we define a dictionary inside a dictionary, it is known as a nested dictionary.
Example:
Behind the code
In the above code, we have declared a variable nest_dic , which is a dictionary data type, but we will call it a nested dictionary because it has 2 dictionaries inside itself.
Create a Python Nested Dictionary
Let’s create 2 dictionaries inside a dictionary:
Behind the code
In the above code, our main dictionary is mobiles and it has two keys 1 & 2, and both the keys have their own dictionaries as values.
Access Elements of a Nested Dictionary
Like with a normal dictionary, we use square brackets for accessing a nested dictionary and the keys to get the corresponding values. In a nested dictionary, if we want to access the values then we have to use 2 square bracket pairs.
Example:
Output:
Examples:
Add Elements to the nested dictionary:
Output:
Behind the code
In the above example, we add a new dictionary in mobiles. F irst, we create a new dictionary at mobiles[3] then place values in that dictionary with the help of keys.
There is another simple approach for adding a dictionary inside a dictionary.
Let’s understand it with an example:
Delete Elements from a Python Nested Dictionary
Python has a keyword del that we use to delete objects. So, in a dictionary, we can also delete items with the help of this del keyword.
Example to delete an element from a nested dictionary:
Output:
Behind the code
In the above example, we delete the price key and its values for each nested dictionary.
Delete a Python Nested Dictionary
As we have deleted the price element for each dictionary using the del keyword, we can also delete the nested dictionary using the same.
Example:
Output:
Iterating Through a Nested Dictionary
We can iterate over the items of nested dictionaries with the help of for loop.
Example:
Output:
Points to Remember
- A nested dictionary is a dictionary inside a dictionary.
- Only the values of a dictionary can be a dictionary because dictionaries are mutable.
- Once a dictionary is created, we can add and delete items from it.
- We can access the nested dictionary using the parent dictionary key.