How do you create nested dict in Python? How to Access, add and delete elements from a Nested Dictionary? Let’s discuss everything about the nested dictionary in this post.

I assume that you know what actually a dictionary is in python?

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:

Create a Nested Dictionary

A nested dictionary can be created using {} (curly braces) inside of parent dictionary.

dict() Constructor

You can also create a nested dictionary using dict() constructor. All we need to do is to pass the internal dictionary as a key-value pair.

output

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.

output

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.

output

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.

output

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.

del – Use del statement when you don’t need the item’s value which is being deleted.

popitem() – Removes the last item of the dictionary.

Iterate through Nested Dictionary

You can easily iterate through a nested dictionary using nested for loop.

output

In the above example, we are checking each value if it is a dictionary, if YES then we iterate through the value using nested for loop to print key: value pairs else we directly print them.

Merge two Nested Dictionary

Python has a builtin update() method to merge two dictionaries. See the source code below to understand how it works.

output

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.

Leave a Reply