Add keys to nested Dictionary in Python

In this tutorial, you will learn how to add keys to a nested dictionary in Python.

A Dictionary in Python is an unordered collection of values. It stores those values in a pair key: value, where each key can hold only 1 value.
A nested Dictionary as the name states is a dictionary inside a dictionary.

There are 2 methods through which we can add keys to a nested dictionary.
One is using the dictionary brackets and the other using the update() method.

Also, read: Merge multiple dictionaries in Python

 

Method 1

This is the easiest method through which we can add keys to the nested Dictionary in Python. This is done by nesting the dictionary. When we add the nested dictionary with a new value, the new key is generated automatically.

test_dict = {'DOB' : {'DATE' : 1, 'MONTH' : 1}}
print('Original Dictionary was :\n'+str(test_dict))
#updating the dictionary 
test_dict['DOB']['YEAR']=1999
#printing the dictionary
print('Updated Dictionary is :\n'+str(test_dict))

And below is the output result:

Original Dictionary was :
{'DOB': {'DATE': 1, 'MONTH': 1}}
Updated Dictionary is :
{'DOB': {'DATE': 1, 'MONTH': 1, 'YEAR': 1999}}

Method 2

We use the update() method which accepts the dictionary and adds the keys to it.
Note: When multiple keys have to be added this method is used.

test_dict = {'Address' : {'HouseNo.' : 100, 'Street' :'ABC Street'}}
dict2={'Locality':'XYZ','State':'PQR','Country':'INDIA'}
print('Original Dictionary was :\n'+str(test_dict))

#updating dictionary using update method 
test_dict['Address'].update(dict2)
print('Updated Dictionary is :\n'+str(test_dict))

The output of our above program will be:

Original Dictionary was :
{'Address': {'HouseNo.': 100, 'Street': 'ABC Street'}}
Updated Dictionary is :
{'Address': {'HouseNo.': 100, 'Street': 'ABC Street', 'Locality': 'XYZ', 'State': 'PQR', 'Country': 'INDIA'}}

 

Leave a Reply

Your email address will not be published. Required fields are marked *