Summary: In this tutorial, you will learn about different types of nested dictionaries in Python. In addition, you will also learn about different operations that are applicable to a dictionary such as accessing an item, adding and deleting items from a nested dictionary, etc.
A dictionary can contain another dictionary, which in turn can contain another dictionary inside of it and so on. If this nesting of dictionary even occurs for one time then we say that the dictionary is nested.
Example:
d = { 'title': 'nested dict',
'lang': {'name':'python', 'version': '3.+'}}
Create a Nested Dictionary
A nested dictionary can be created using {} (curly braces) inside of the parent dictionary.
d = { 'title': 'nested dict',
'lang': {'name':'python', 'version': '3.+'}}
dict() Constructor
You can also create a nested dictionary using the dict()
constructor. All we need to do is to pass the internal dictionary as a key-value pair.
d = dict(title = 'nested dict',
lang = {'name':'python', 'version': '3.+'})
print(d)
Output:
{'lang' : {'version': '3.+', 'name': 'python'}, 'title': 'nested dict'}
In the above example, we have created a nested dictionary ‘d’ which has another dictionary inside of it as ‘lang’.
Access Nested Dictionary Items
To access an item of a dictionary simply specify its corresponding key inside of square brackets as shown below.
d = { 'title': 'nested dict',
'lang': {'name':'python', 'version': '3.+'}}
print(d['title'])
print(d['lang']['name'])
Output:
nested dict python
If you try to access an item which is not available in the dictionary, eg d['ide']
the compiler will throw KeyError: 'ide'
.
In this case,I recommend you to use get()
method because get() method returns None
instead of error if the key is not present in the dictionary.
d = { 'title': 'nested dict',
'lang': {'name':'python', 'version': '3.+'}}
print(d.get('lang').get('name'))
print(d.get('ide'))
Output:
python None
Add or Update Nested Dictionary Items
You can easily add a new item to the nested dictionary by referring to the key and assigning the value to it.
d = { 'title': 'nested dict',
'lang': {'name':'python', 'version': '3.+'}}
d['author'] = { 'name': 'Adarsh', 'website': 'https://pencilprogrammer.com'}
d['title'] = 'Add Item to Dictionary'
print(d)
Output:
{'title' : 'Add Item to Dictionary', 'lang' : {'version': '3.+', 'name': 'python'}, 'author': {'website': 'https://pencilprogrammer.com', 'name': 'Adarsh'}}
If the key is new then the item gets added to the dictionary else the existing item’s value gets updated with the new value.
Remove Item from Nested Dictionary
You can easily remove an item from the dictionary using any of the following.
pop() – This method removes the specific item by key and returns its value at the end of operation.
d = { 'title': 'Remove Item',
'lang': {'name':'python', 'version': '3.+'}}
print(d.pop('lang')) # {'name':'python', 'version': '3.+'}
print(d) # {'title': 'Remove Item'}
del – Use del
statement when you don’t need the item’s value that is being deleted.
d = { 'title': 'Delete Item',
'lang': {'name':'python', 'version': '3.+'}}
del d['lang']
print(d) # {'title': 'Delete Item'}
popitem() – Removes the last item of the dictionary.
d = { 'title': 'Delete Item',
'lang': {'name':'python', 'version': '3.+'}}
d.popitem()
print(d) # {'title': 'Delete Item'}
Iterate through Nested Dictionary
You can easily iterate through a nested dictionary using a nested for loop.
d = { 'title': 'Nested Dictionary Python',
'lang': {'name':'python', 'version': '3.+'}}
for key, val in d.items():
#iterate once more if value is another dictionary
if type(val) is dict:
for nesKey, nesVal in val.items():
print(nesKey+':', nesVal)
else:
print(key+':', val)
Output:
title: Nested Dictionary Python version: 3.+ name: python
In the above example, we are checking each value if it is a dictionary, if YES then we iterate through the value using a nested for loop to print key: value pairs else we directly print them.
Merge two Nested Dictionary
Python has a built-in update()
method to merge two dictionaries. See the source code below to understand how it works.
d1 = { 'title': 'Nested Dictionary Python',
'lang': {'name':'python', 'version': '3.+'}}
d2 ={ 'title': 'Merge Dictionaries',
'author': { 'name': 'Adarsh', 'website': 'https://pencilprogrammer.com'}}
d1.update(d2)
print(d1)
Output:
{'lang': {'name': 'python', 'version': '3.+'}, 'title': 'Merge Dictionaries', 'author': {'website': 'https://pencilprogrammer.com', 'name': 'Adarsh'}}
Note beside merging the 2 dictionaries, the common key ‘title’ also got updated with the new value. So it is advised to use it when strongly needed.
That’s all for the nested dictionary tutorial. If you have any doubts or suggestion then please comment below.