Adding two dictionaries in python

Merge Dictionaries in Python (8 different methods)

In this python tutorial, we will discuss the Python concatenate dictionary.

There are eight ways to merge or concatenate dictionaries in Python, which are shown below:

  1. Using the update() method
  2. Using the double-asterisk notation (unpacking)
  3. Using the dictionary constructor
  4. Using the ChainMap()
  5. Using the union operator (|)
  6. Using chain() method
  7. Using the dictionary comprehension
  8. Using the reduce() function

Python concatenate dictionary

In some cases, you may need to concatenate two or more dictionaries together to create a larger dictionary. There are several ways to concatenate dictionaries in Python, including using the update() method, the ** operator, and the chain() method from the itertools module and etc.

Method-1: Python concatenate dictionary using the update() method

The update() method merges the keys and values of one dictionary into another.

# Define two dictionaries containing different key-value pairs dictionary1 = dictionary2 = # Use the update() method to add the key-value pairs from dictionary2 to dictionary1 dictionary1.update(dictionary2) # Print the updated dictionary1, which now contains all the key-value pairs from both dictionaries print(dictionary1) 

The above code defines two dictionaries containing different key-value pairs. The code then uses the update() method to add the key-value pairs from dictionary2 to dictionary1.

  • Finally, the code prints the updated dictionary1, which now contains all the key-value pairs from both dictionaries.
Читайте также:  Reference class java example

Python concatenate dictionaries

Method-2: Python concatenate dictionary using the double-asterisk notation (unpacking)

The double-asterisk notation (**dict) can be used to unpack a dictionary and merge it with another.

# Define two dictionaries containing different key-value pairs dict1 = dict2 = # Use dictionary unpacking to merge the two dictionaries into a single dictionary merged_dict = <**dict1, **dict2># Print the merged dictionary print(merged_dict) 

The above code defines two dictionaries dict1 and dict2 with different key-value pairs. It then uses dictionary unpacking to merge these two dictionaries into a single dictionary called merged_dict. Finally, it prints the merged dictionary.

Method-3: Python concatenate dictionary using the dictionary constructor

The dictionary constructor can be used to create a new dictionary by merging two or more dictionaries.

# Define two dictionaries containing different key-value pairs dict1 = dict2 = # Use the dict() constructor and dictionary unpacking to merge the two dictionaries into a single dictionary merged_dict = dict(dict1, **dict2) # Print the merged dictionary print(merged_dict) 

The above code defines two dictionaries dict1 and dict2 with different key-value pairs.

  • It then uses the built-in dict() constructor along with dictionary unpacking to merge these two dictionaries into a single dictionary called merged_dict.
  • Finally, it prints the merged dictionary.

Method-4: Python concatenate dictionary using the ChainMap()

The ChainMap() class from the collections module can be used to concatenate dictionaries by creating a mapping of several dictionaries.

# Import the ChainMap class from the collections module from collections import ChainMap # Define two dictionaries containing different key-value pairs dict1 = dict2 = # Use the ChainMap class to merge the two dictionaries into a single dictionary merged_dict = ChainMap(dict1, dict2) # Convert the merged dictionary into a regular dictionary and print it print(dict(merged_dict)) 

The code first imports the ChainMap class from the collections module. It then defines two dictionaries dict1 and dict2 containing different key-value pairs.

  • The ChainMap class is then used to merge these two dictionaries into a single dictionary called merged_dict.
  • Finally, the dict() constructor is used to convert the merged dictionary into a regular dictionary and the resulting dictionary is printed.

Method-5: Python concatenate dictionary using the union operator (|)

Starting from Python 3.9, you can use the union operator (|) to concatenate dictionaries.

# Define two dictionaries containing different key-value pairs dict1 = dict2 = # Use the union operator to merge the two dictionaries into a single dictionary merged_dict = dict1 | dict2 # Print the resulting merged dictionary print(merged_dict) 

The code above code defines two dictionaries containing different key-value pairs. The union operator | is then used to merge the two dictionaries into a single dictionary called merged_dict. Finally, the merged dictionary is printed.

Python Concatenate Dictionary Using the Union

Method-6: Python concatenate dictionary using chain() method

The chain() method from the itertools module can be used to combine multiple iterables into a single iterable. When used with dictionaries, the keys and values from each dictionary are merged into a single iterator, which can be used to create a new dictionary.

# Import the itertools module import itertools # Define two dictionaries containing different key-value pairs dict1 = dict2 = # Create an empty dictionary called merged_dict merged_dict = <> # Use itertools.chain() to chain the items from both dictionaries, and then loop through them for key, value in itertools.chain(dict1.items(), dict2.items()): merged_dictAdding two dictionaries in python = value # Print the resulting merged dictionary print(merged_dict) 

The code imports the itertools module and defines two dictionaries called dict1 and dict2. The program then creates an empty dictionary merged_dict.

  • Using the itertools.chain() function, the code combines the key-value pairs from both dictionaries into a single iterable, which is then looped through with a for loop.
  • The loop assigns the key-value pairs to the key and value variables and adds them to merged_dict.

Method-7: Python concatenate dictionary using the dictionary comprehension

Dictionary comprehension is a concise and readable way to create a dictionary from an iterable. When used with multiple dictionaries, it can be used to merge them into a single dictionary.

# Define two dictionaries with key-value pairs dict1 = dict2 = # Merge the key-value pairs from both dictionaries into a single dictionary using a dictionary comprehension merged_dict = # Print the resulting merged dictionary print(merged_dict) 

The above code defines two dictionaries dict1 and dict2 and creates a new dictionary merged_dict.

  • It then merges the key-value pairs from both dictionaries into merged_dict using dictionary comprehension. Finally, it prints out the resulting merged_dict.

Method-8: Python concatenate dictionary using the reduce() function

The reduce() function from the functools module can be used to concatenate a list of dictionaries.

# Import the reduce function from the functools module from functools import reduce # Define a list of dictionaries with key-value pairs dicts = [, , ] # Use reduce to merge the key-value pairs from all dictionaries into a single dictionary # The lambda function merges two dictionaries using the unpacking syntax and returns the result merged_dict = reduce(lambda d1, d2: <**d1, **d2>, dicts) # Print the resulting merged dictionary print(merged_dict) 

The above code imports the reduce function from the functools module and creates a list of three dictionaries.

  • It then uses the reduce function to merge the dictionaries into a single dictionary. The lambda function takes two dictionaries as inputs and merges them using the unpacking operator ** . Finally, the merged dictionary is printed to the console.

Also, take a look at some more Python tutorials.

Conclusion

In this python tutorial, we have learned Python concatenate dictionary using the different approaches:

  • Using the update() method
  • Using the double-asterisk notation (unpacking)
  • Using the dictionary constructor
  • Using the ChainMap()
  • Using the union operator (|)
  • Using chain() method
  • Using the dictionary comprehension
  • Using the reduce() function

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to Merge Dictionaries in Python

Ashutosh Krishna

Ashutosh Krishna

How to Merge Dictionaries in Python

In Python, a dictionary is a collection you use to store data in pairs. It is ordered and mutable, and it cannot store duplicate data.

We write a dictionary using curly brackets like this:

Sometimes, we need to merge two or more dictionaries to create a bigger dictionary. For example:

dict_one = < "id": 1, "name": "Ashutosh", "books": ["Python", "DSA"] >dict_two = < "college": "NSEC", "city": "Kolkata", "country": "India" >merged_dict =

In the merged_dict we have the key-value pairs of both dict_one and dict_two . This is what we wish to achieve programmatically.

There are various ways we can do this in Python:

  1. Using a for loop
  2. Using the dict.update() method
  3. Using the ** operator
  4. Using the | (Union) operator (for Python 3.9 and above)

Let’s explore each way one after another.

How to Merge Dictionaries in Python Using a For Loop

We can merge two or more dictionaries using for loop like this:

>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> for key,value in dict_two.items(): . merged_dictAdding two dictionaries in python = value . >>> merged_dict >>> for key,value in dict_three.items(): . merged_dictAdding two dictionaries in python = value . >>> merged_dict

But the problem with this method is that we need to run so many loops to merge the dictionaries.

How to Merge Dictionaries in Python Using the dict.update() Method

If you explore the dict class, there are various methods inside it. One such method is the update() method which you can use to merge one dictionary into another.

>>> dict_one = < . "id": 1, . "name": "Ashutosh", . "books": ["Python", "DSA"] . >>>> dict_two = < . "college": "NSEC", . "city": "Kolkata", . "country": "India" . >>>> dict_one.update(dict_two) >>> dict_one

But the problem when we use the update() method is that it modifies one of the dictionaries. If we wish to create a third dictionary without modifying any of the other dictionaries, we cannot use this method.

Also, you can only use this method to merge two dictionaries at a time. If you wish to merge three dictionaries, you first need to merge the first two, and then merge the third one with the modified dictionary.

>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> dict_one.update(dict_two) >>> dict_one >>> dict_one.update(dict_three) >>> dict_one

Let’s explore some other options.

How to Merge Dictionaries in Python Using the ** operator

You can use the double-asterisk (**) method to unpack or expand a dictionary like this:

>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"] . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> merged_dict = <**dict_one, **dict_two, **dict_three>>>> merged_dict

Using the ** operator to merge the dictionaries doesn’t affect any of the dictionaries.

How to Merge Dictionaries in Python Using the | Operator

Starting with Python 3.9, we can use the Union ( | ) operator to merge two or more dictionaries.

>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> merged_dict = dict_one | dict_two | dict_three >>> merged_dict

This is the most convenient method available for merging dictionaries in Python.

Conclusion

We have explored several different methods for merging dictionaries. If you have Python 3.9 or above, you should use the | operator. But if you use older versions of Python, you can still use the other methods discussed above.

Ashutosh Krishna

Ashutosh Krishna

Application Developer at Thoughtworks India

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Оцените статью