What are nested dictionaries?

A dictionary is a data structure used in Python. It is very similar to an array except that it is of an associative nature. A dictionary consists of key-value pairs where each value in the array can be identified by a unique key.

What is a nested dictionary?

A nested dictionary is a dictionary inside a dictionary.

This concept in Python is very similar to that of a nested lista list inside a list.

A nested dictionary contains keys where each key is a unique dictionary itself.

widget

Code: Nested dictionary

As shown above, a key is linked to nested keys, and each of these nested keys have different key-value pairs.

Below is a simple code to create a nested dictionary.

main_dict = dict()
nested_dict1 = dict()
nested_dict2 = dict()
nested_dict1['Animal'] = ['Cat','Dog','Lion']
nested_dict2['Bird'] = ['Crow','Eagle']
main_dict['1'] = nested_dict1
main_dict['2'] = nested_dict2
print(main_dict)

Code: Accessing values

Similarly, to access a value inside a nested dictionary, we can use the following method:

main_dict = dict()
nested_dict1 = dict()
nested_dict2 = dict()
nested_dict1['Animal'] = ['Cat','Dog','Lion']
nested_dict2['Bird'] = ['Crow','Eagle']
main_dict['1'] = nested_dict1
main_dict['2'] = nested_dict2
#To access cat we will give 2 keys and the index
print(main_dict['1']['Animal'][0])

Free Resources