Updated February 10, 2023
Introduction to Nested Dictionary Python
A nested dictionary in python is a dictionary that further contains another dictionary up to arbitrary depth. Nested dictionaries are similar to “records” or “structs” as they are also used to represent structural information. Dictionary stores information as a collection of key-value pairs. Nested dictionaries in Python are an unordered collection of one or two dictionaries.
Key Takeaways
Python supports the concept of dictionaries. These are mutable. Thus, adding, deleting, and replacing items from dictionaries is easy.
Below are the things you must know about nested dictionaries.
- Data is stored in key-value pairs.
- In a dictionary, the first part is the data set, and the second is the key value.
- You cannot include duplicate values in a dictionary.
- A nested dictionary stores an unordered collection of other dictionaries.
- You can refer to the key to access the corresponding data.
- To create a nested dictionary in Python, you must separate dictionaries with commas enclosed within braces.
- You can shrink or grow the dictionary as required.
What is a Nested Dictionary in Python?
A nested dictionary means a dictionary within another dictionary. In Python, the nested dictionary is the concept of representing structural information, where the data is stored in key-value pairs. It is a collection of unordered data items without duplicate items.
Syntax of Python nested dictionaries:
nested_dict = { 'dict1': {'key1': 'value1'}, 'dict2': {'key2': 'value2'}}
How to Create a Nested Dictionary Python?
To create a nested dictionary in Python, you must place commas to separate different dictionaries enclosed within the braces.
For example:
nes_dict = {'dict1': {'Color': 'Yellow', 'Shape': 'Triangle'}, 'dict2': {'Color': 'Orange', 'Shape': 'Line'}}
print (nes_dict)
Output:
Now we are creating a dictionary to store employees’ records, as below.
Code:
D = {'emp1': {'name': 'sima', 'job': 'Dev'},
'emp2': {'name': 'rema', 'job': 'tester'},
'emp3': {'name': 'geta', 'job': 'IT'}}
Output:
dict() Constructor
You can use the type constructor dict() to create a nested dictionary. For creating a nested dictionary, pass a dictionary key: value pair as keyword arguments to the dict() Constructor, as shown below.
For example:
Code:
D = dict(emp1 = {'name': 'reta', 'job': 'dev'},
emp2 = {'name': 'meta', 'job': 'tester'},
emp3 = {'name': 'seta', 'job': 'IT'})
print(D)
Output:
You can combine the dict() and zip() functions to combine the dynamically obtained lists of keys and values at runtime.
For example:
Code:
IDs = ['e1','e2','e3']
EInfo = dict(e1 = {'name': 'reta', 'job': 'dev'},
e2 = {'name': 'meta', 'job': 'tester'},
e3 = {'name': 'seta', 'job': 'IT'})
D = dict(zip(IDs, EInfo))
print(D)
Output:
For creating dictionaries with default values for each key, you can use the fromkeys() method, as shown below.
For example:
Code:
IDs = ['e1','e2','e3']
Defaults = {'name': '', 'job': ''}
D = dict.fromkeys(IDs, Defaults)
print(D)
Output:
Examples of Nested Dictionary Python
Given below are the examples mentioned:
Example #1
Accessing items from the nested dictionary. To access an item from the nested dictionary, you must specify the key in multiple square brackets, as shown below.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'tester'},
'e3': {'name': 'reta', 'job': 'Developer'}}
print(D['e1']['name'])
print(D['e2']['job'])
Output:
An exception will be thrown if you try to refer to a key that does not exist in the nested dictionary. Suppose you use the following key (salary) to access the employee information; you will get an error.
Code:
print(D['emp1']['salary'])
Output:
You must use a dictionary, get() method to avoid such errors. If the value for that key is present in the dictionary, it will return the corresponding value else, “None”. No error will be raised in this case.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'tester'},
'e3': {'name': 'reta', 'job': 'Developer'}}
print(D['e1'].get('salary'))
Output:
Example #2
Changing items in a nested dictionary. To make any changes in the existing nested dictionary, you need to refer to the key and assign a new value.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'Tester'},
'e3': {'name': 'geta', 'job': 'OPs'}}
D['e3']['name'] = 'Max'
D['e3']['job'] = 'tutor'
print(D['e3'])
Output:
Example #3
Adding or updating items in a nested dictionary.
To add or update the items in a nested dictionary, you need to refer to the key and assign a value. The value will be replaced if the key is already in the dictionary.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'Tester'},
'e3': {'name': 'geta', 'job': 'OPs'}}
D['e3'] = {'name': 'reta', 'job': 'ops'}
print(D)
Output:
In the above example, the key is new, and the key value is added to the dictionary.
Example #4
Merging two nested dictionaries.
To merge nested dictionaries, python offers a built-in update() method to merge the keys and values of one nested dictionary into another. But before you start merging, you must know that this method will blindly overwrite the values of the same key even if there is a clash.
Code:
D1 = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'reta', 'job': 'Dev'}}
D2 = {'e2': {'name': 'geta', 'job': 'tester'},
'e3': {'name': 'sam', 'job': 'ops'}}
D1.update(D2)
print(D1)
Output:
In the above example, the ’e2′ record is updated while ’e3′ is added to the dictionary.
Example #5
Removing items from the nested dictionary.
For removing items from the nested dictionary, you can use different methods. Removing items using the key. If you know the key for the item to be deleted, use the pop() method. It will remove the key and return the value.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'Tester'},
'e3': {'name': 'geta', 'job': 'OPs'}}
x = D.pop('e3')
print(D)
print(x)
Output:
If you do not want to get the removed value, you can use the “del” statement.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'Tester'},
'e3': {'name': 'geta', 'job': 'OPs'}}
del D['e3']
print(D)
Output:
Example #6
Removing the last inserted item from the nested dictionary. For removing the last inserted item, you can use the popitem() method.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'Tester'},
'e3': {'name': 'geta', 'job': 'OPs'}}
x = D.popitem()
print(D)
print(x)
Output:
Example #7
Iterating through the nested dictionary. You can use the nested for loop to iterate through all the values in the nested dictionary.
Code:
D = {'e1': {'name': 'seta', 'job': 'IT'},
'e2': {'name': 'meta', 'job': 'Tester'},
'e3': {'name': 'geta', 'job': 'OPs'}}
for id, info in D.items():
print("\nEmp ID:", id)
for k in info:
print(k + ':', info[k])
Output:
Conclusion
Python is a well-known and widely adopted language to cater to different challenges in this modern-age competitive market. Python supports an essential concept of nested dictionaries storing a dictionary within another. It contains information in a key-value pair, where you can access the value using its key. It is an unordered collection of dictionaries where you can perform several tasks on nested dictionaries, such as adding, deleting, updating, and traversing items of a nested dictionary. This article has explained each case with easy examples and output.
Recommended Articles
This is a guide to Nested Dictionary Python. Here we discuss the introduction, how to create a nested dictionary python, and examples. You may also have a look at the following articles to learn more –