Python - How To Add Dictionary to Dictionary in Python

ID : 188

viewed : 113

Tags : PythonPython Dictionary

vote vote

93

A dictionary in Python constitutes a group of elements in the form of key-value pairs. It is an unordered and mutable collection.

We will discuss different methods to append a dictionary to another dictionary in Python in this tutorial.

Use the update() Method to Add a Dictionary to Another Dictionary in Python

The update() method concatenates one dictionary to another dictionary. Using this method, we can insert key-value pairs of one dictionary to the other dictionary.

For example,

D1 = {"loginID":"xyz","country":"USA"} D2 = {"firstname":"justin","lastname":"lambert"} D1.update(D2) print(D1) 

Output:

{'loginID': 'xyz', 'country': 'USA', 'firstname': 'justin', 'lastname': 'lambert'} 

In the above code, we have concatenated the dictionary D1 and D2 using the update() method.

Note that in this method, the first dictionary gets updated with the values of the second dictionary. In our example, D1 got updated.

Use Dictionary Unpacking Operator ** to Add a Dictionary to Another Dictionary in Python

We can add two dictionaries in Python and store their combination in a third dictionary using the . This method does not change the key-value pairs of the original dictionary.

This operator works from Python 3.5.

For example,

def merge(D1,D2):     py={**D1,**D2}     return py D1 = {"loginID":"xyz","country":"USA"} D2 = {"firstname":"justin","lastname":"lambert"} D3 =(merge(D1,D2)) print(D3) 

Output:

{'loginID': 'xyz', 'country': 'USA', 'firstname': 'justin', 'lastname': 'lambert'} 

In the above code, we have used ** in Python to add the first dictionary D1 and the second dictionary D2 in a separate third dictionary, D3.

Use the | Operator to Add a Dictionary to Another Dictionary in Python

We can use this operator in the latest update of Python (Python 3.9). It is an easy and convenient method to merge two dictionaries.

In the following code snippet, we use the | operator.

def Merge(D1,D2):     py = D1 | D2     return py D1 = {"RollNo": "10", "Age":"18"} D2 = {"Marks": "90", "Grade": "A"} D3 = Merge(D1, D2) print(D3) 

Output:

{'RollNo': '10', 'Age':'18' ,'Marks': '90', 'Grade': 'A'} 

Use the collections.ChainMap Container to Add a Dictionary to Another Dictionary in Python

ChainMap is used for mapping many dictionaries into one unit. We have to import it from the collections module.

We use the ChainMap() constructor to create a ChainMap container while passing the dictionaries we want to combine as a set of arguments.

See the following code.

from collections import ChainMap D1 = {'w':1,'x':2} D2 = {'y':3, 'z':4} D3 = ChainMap(D1,D2) D3 = {k: v for d in (D1, D2) for (k, v) in d.items()} print(D3) 

Output:

{'w': 1, 'x': 2, 'y': 3, 'z': 4} 

This method works in Python 2.7 and above.

  • Related HOW TO?