How to add Dictionary to Dictionary in Python?

Hello folks, today we are going to how to add a dictionary to a dictionary in Python.

Adding Dictionary to a Dictionary

Consider two dictionaries d1 and d2

d1 = {‘name’ : ‘Warner’ , ‘roll’ : ‘259’ , ‘school’ : ‘GVD’}

d2 = {‘Grade’:’A’ , ‘Rank’ : ‘2’}

Method1

Steps:

  • Declare two dictionaries d1 and d2
  • Iterate through second dictionary and add the key and values to first dictionary
  • Now d1 is the required dictionary

Code:

d1 = {'name' : 'Warner' ,
      'roll' : '259' ,
      'school' : 'GVD'}

d2 = {'Grade':'A' ,
      'Rank' : '2'}

for key in d2:
  d1[key] = d2[key]
print(d1)

Output:

{'name': 'Warner', 'roll': '259', 'school': 'GVD', 'Grade': 'A', 'Rank': '2'}

 

Method2:

We can concatenate two dictionaries using update()

Code:

d1 = {'name' : 'Warner' ,
      'roll' : '259' ,
      'school' : 'GVD'}

d2 = {'Grade':'A' ,
      'Rank' : '2'}
d1.update(d2)
print(d1)

Output:

{'name': 'Warner', 'roll': '259', 'school': 'GVD', 'Grade': 'A', 'Rank': '2'}

Don’t stop learning!!!

Leave a Reply

Your email address will not be published.