5 Error-proof Ways to Merge Dictionaries in Python

python merge dictionaries

Find out how Python merges dictionaries with these five bullet-proof methods and techniques!

Dictionaries are one of the most helpful data structure resources that Python has to offer. Understanding how Python merge dictionaries is an essential step in any coder’s journey, and thankfully, there are several ways to perform this equally essential and common task.

A dictionary data type is essentially an unordered collection of data elements grouped in key-value pairs. Dictionaries, and their key-value pairs, are defined inside curly brackets, with each pair separated by a single comma. A semi-colon between them separates the Key and value elements. A dictionary’s index can use all sorts of data types (unlike lists, which strictly use integers).

Python Merge Dictionaries

Figuring out how Python merge dictionaries is pretty simple. There are well over five methods to successfully merge dictionaries in Python, but today, we’ve hand-picked the 5 best ways to make a Python dictionary merge as simple and error-proof as possible.
Without further ado, let’s find out how to merge dictionaries in Python!

Python Dictionary Merge with The Merge Operator

This straightforward operator can only be used in Python 3.9 version and above!
This technique is hands down, the best way to perform a clean Python dictionary merge. Python introduced the merge operator for dictionaries on October 5th, 2020, and it has quickly become the go-to resource for a quick, pain-free Python dictionary merge.

Here are some of its pros and cons:

Pros

  • Easy to use and convenient.

Cons

  • Only works in Python version 3.9 and above.
  • Can merge multiple dictionaries at the same time.

Observations:

If you’re working with common keys, the new dictionary’s key will use the latter key’s value and overwrite the former ones (the example below will briefly explain what this means).

Let’s figure out how to use this powerful operator for a typical Python dictionary merge.

# Merging three Python dictionaries using the merge (|) operator. Works in Python 3.9 and above

dictionary_one = {
"A": 1,
"B": "2",
}
dictionary_two = {
"C": ["3", "4"],
"D": "5",
}
dictionary_three = {
"B": "6",
"E": "7"
}
merged_dictionary = dictionary_one | dictionary_two | dictionary_three
print (merged_dictionary)

Output

{'A': 1, 'B': '6', 'C': ['3', '4'], 'D': '5', 'E': '7'}

In our example above, we’ve defined our three dictionaries and then proceeded to merge all dictionaries and save their items under an entirely new dictionary. This operator also allows us to preserve our original dictionaries’ values, which is excellent!

Did you notice the “B” key in both the first and third dictionaries? This is commonly known as a common key (or shared key). In our example, the “B” key is a common key, and Python has automatically assigned the third’s dictionary assigned value (6). Python will default to the latter key’s value when merging dictionaries with this and many other techniques and methods.

You can also use the |= operator to merge dictionaries. This modified operator forces Python to operate on the first dictionary, which is perfect if you don’t want to reassign values to a new dictionary. We don’t have any shared keys in this second example, but the same rules apply!

# Merging two Python dictionaries using the merge (|=) operator. Works in Python 3.9 and above.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1 |= dict2
print(dict1)

Output:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Merge Dictionaries in Python with The Unpack Operator

The unpack operator used to be the default tool to merge dictionaries.
Before introducing the merge/pipe operator, the Unpack operator ** was the go-to tool to merge dictionaries in Python. You essentially merge two dictionaries and store all their keys and value pairs into a third dictionary. Kwargs accept named arguments and thus are ideal for unpacking dictionaries.

Pros

  • Straightforward to execute
  • Can merge more than two dictionaries at a time
  • Won’t operate on a pre-existing dictionary

Cons

  • This method only works if the keys of the second dictionary are strings.

Observations:

Like the merge operator, the new dictionary’s key will use the last common key value and overwrite any previous common value.

For the following example, I’ll create three new dictionaries with some of my favorite movie actors and movies and merge them using the unpack operator.

# Merging two Python dictionaries using the unpack (**) operator.

d1 = {'Dustin Hoffman': 'Rain Man',
'Jack Nicholson': 'The Shining',
'Al Pacino': 'Heat'}
d2 = {'Robert De Niro': 'Goodfellas',
'Leonardo DiCaprio': 'The Departed'}
d3 = {'Brad Pitt': 'Seven',
'Robin Williams': 'Good Will Hunting'}

d3 = {**d1, **d2, **d3}

print(d3)

Output:

{'Dustin Hoffman': 'Rain Man', 'Jack Nicholson': 'The Shining', 'Al Pacino': 'Heat', 'Robert De Niro': 'Goodfellas', 'Leonardo DiCaprio': 'The Departed', 'Brad Pitt': 'Seven', 'Robin Williams': 'Good Will Hunting'}

The process is straightforward, and the result has been stored in a new dictionary (d3). The example above proves you can merge dictionaries in Python without using the merge operator; in fact, you can merge more than two at a time, saving you significant time and effort!

Please remember that the dictionary merge will only work if the second dictionary’s keys are strings!

The next block of codes demonstrates the kind of error you’ll get if you forget to turn your keys into strings and how to fix that.

# Merging two Python dictionaries using the unpack (**) operator. Keys need to be strings, else it won't work.

x = {1: 'A', 2: 'B'}
y = {3: 'C', 4: 'D'}
z = dict(x, **y)
print(z)

Output:

Traceback (most recent call last):
File "c:\Users\Dan\Desktop\Python Files\Dictionaries Merge Error.py", line 5, in
z = dict(x, **y)
TypeError: keywords must be strings

# Merging two Python dictionaries using the unpack (**) operator. Keys need to be strings, else it won't work.

x = {1: 'A', 2: 'B'}
y = {"3": 'C', "4": 'D'}
z = dict(x, **y)
print(z)

Output:

{1: 'A', 2: 'B', '3': 'C', '4': 'D'}

Merge Two Dictionaries Python With a For Loop

We can merge two dictionaries Python, with a for loop that iterates over each key-value pair in the second dictionary and merges them into the first dictionary. Unfortunately, this method will also overwrite common keys’ values with the second dictionary keys’ values. Here are this method’s pros and cons.

Pros

  • Easy to adapt and execute.

Cons

  • Works with two dictionaries at a time.
  • Somewhat clunky, and it makes your code look unnecessarily cluttered.

Observations:

Best to include a developer comment that explains what these lines of code do since most coders use the first two methods in this article.

For this example, we’ll use two dictionaries featuring some of my favorite actresses and movies.

# Merging two dictionaries using a For Loop

dictionary_1 = {'Meryl Streep': "Kramer vs Kramer", 'Jodie Foster': "Silence of the Lambs"}
dictionary_2 = {'Sigourney Weaver': "Alien", 'Charlize Theron': "The Devil's Advocate"}
for key, value in dictionary_2.items():
dictionary_1[key] = value
print(dictionary_1)

Output:

{'Meryl Streep': 'Kramer vs Kramer', 'Jodie Foster': 'Silence of the Lambs', 'Sigourney Weaver': 'Alien', 'Charlize Theron': "The Devil's Advocate"}

As you can tell, the process is relatively simple, but it’s also very clunky and slow, especially because you can only merge two dictionaries at a time. This method will force you to create more and more loops as you continue to merge new dictionaries.
Python Merging Dictionaries while Preserving Shared Keys Values

For our following method, we’ll combine two of the tools we’ve already covered: Python merging dictionaries with the Unpack operator and a for loop. In doing so, we’ll be able to preserve all values assigned to common keys across dictionaries.

Pros

  • Easy to use and convenient.
  • Allows you to visualize values assigned to common keys.

Cons

  • Works with two dictionaries, making it a potentially slow process.

Observations:

It’s highly recommended you drop a developer comment explaining what these blocks of codes are doing. Another collaborator might overlook your wishes to preserve values from common keys.

For this example, I’ll grab my initial dictionary of favorite actors and movies and include some of their other great performances. That way, some of these keys (actors) will have additional values (movies).

# Merging two Python dictionaries while preserving values shared across common keys.

shared_dictionary_1 = {'Robert De Niro': 'Heat',
'Jack Nicholson': 'The Shining',
"Al Pacino": "Heat"}
shared_dictionary_2 = {'Robert De Niro': 'Goodfellas',
"Leonardo DiCaprio": "The Departed",
'Al Pacino': "The Devil's Advocate",
"Robin Williams": 'Good Will Hunting'}

def mergeDictionary(shared_dictionary_1, shared_dictionary_2):
shared_dictionary_3 = {**shared_dictionary_1, **shared_dictionary_2}
for key, value in shared_dictionary_3.items():
if key in shared_dictionary_1 and key in shared_dictionary_2:
shared_dictionary_3[key] = [value , shared_dictionary_1[key]]
return shared_dictionary_3

shared_dictionary_3 = mergeDictionary(shared_dictionary_1, shared_dictionary_2)
print(shared_dictionary_3)

Output:

{'Robert De Niro': ['Goodfellas', 'Heat'], 'Jack Nicholson': 'The Shining', 'Al Pacino': ["The Devil's Advocate", 'Heat'], 'Leonardo DiCaprio': 'The Departed', 'Robin Williams': 'Good Will Hunting'}

As you can see, many of my favorite actors (common keys) now simultaneously display more of their best performances (values) in a new dictionary. You’ll notice we’ve stored these values in a list and assigned it as a key value in our freshly created dictionary.

Python Merge Two Dictionaries: Update Method

The update() method allows Python merge two dictionaries with just a few lines of code. Python updates the keys and values of dictionary #1 with those on dictionary #2, effectively operating on dictionary #1. As with other methods, common key values will take dictionary #2’s values.

Here’s a quick rundown of this Python merge two dictionaries method’s pros and cons:

Pros

  • Easy to use
  • This approach works with Python 2 and Python 3, so it’s the “safest bet” when merging two dictionaries.
  • Operates on a pre-existing dictionary.

Cons

  • Operates on a pre-existing dictionary (this can potentially be a con, so I’ve included it here too).
  • Can’t merge more than two dictionaries at a time.

Observations:

Go-to option when forced to use older versions of Python. Otherwise, it’s best to use the most recent merge operator.

I’ll create a couple of dictionaries with some of the artists and songs on my coding playlist, and Python merge two dictionaries using this method.

# Merging two dictionaries using the Update Method

music_dict_1 = {"You Never Can Tell": "Chuck Berry", "Eli": "Bosnian Raindbows", "Dire Straits" : "Money for Nothing" }
music_dict_2 = {"Detroit Spinners": "Rubberband Man","Space Invader": "The Pretenders","Dire Straits" : "Walk of Life"}
music_dict_1.update(music_dict_2)
print('New Music Dictionary:')
print(music_dict_1)

Output:

{'You Never Can Tell': 'Chuck Berry', 'Eli': 'Bosnian Raindbows', 'Dire Straits': 'Walk of Life', 'Detroit Spinners': 'Rubberband Man', 'Space Invader': 'The Pretenders'}

As you can see, one of the music groups had two songs (values) listed in each dictionary. The update method overwrites the first dictionary, so only the latter value appears on our output.

Review

There are numerous ways to ask Python merge dictionaries, but to keep things brief, I’ve decided to feature the top five easiest and safest ways to merge your dictionaries. Each technique and method has its advantages (and disadvantages!); as always, it all comes down to picking a solution that best suits your current needs and resources.

Some of these methods might seem clunky, but if you’re running a relatively simple program where resources and optimal execution times are not a problem, they might be what your app needs. Once you’ve accumulated a more robust toolkit and mastery over Python, you can re-visit and improve your code as a personal challenge!

Jesus Aveledo
Design and marketing professional with 5+ years of website development experience. Currently discovering the power of Python in synthesizing content, ideas, and resources for my clients