How to Merge Two Dictionaries in a Single Expression

Taking two dictionaries, create a third dictionary that is a merge of the original two.

How to Merge Two Dictionaries in a Single Expression
Photo by Bangkit Ristant on Unsplash

How to Merge Two Dictionaries in a Single Expression in Python

Merge two dictionaries into one new one

Challenge

Taking two dictionaries, create a third dictionary that is a merge of the original two. The first dictionary will be treated as the base dictionary and duplicate keys in the second dictionary will overwrite the first. The solution will be a shallow merge, meaning that nested dictionaries will not be subsequently merged.


Solution

By defining our own function, we fulfill the requirement of merging the two dictionaries in a single expression. The function will be a two-step process: make a copy of the first dictionary, then add the second dictionary’s terms to it.def merge_dictionaries(first_dict, second_dict):
  merged = first_dict.copy()
  merged.update(second_dict)
  return mergedd1 = { "A": "Auron", "B": "Braska", "C": "Crusaders" }
d2 = { "C": "Cid", "D": "Dona" }print(merge_dictionaries(d1,d2))
# {'A': 'Auron', 'B': 'Braska', 'C': 'Cid', 'D': 'Dona'}


Honorable Mentions

Using the (**) Operator

Starting in Python 3.5, the the double asterisk can be used to unpack a dictionary. Leveraging dictionary comprehension and the unpacking operator, we can merge the two dictionaries in a single expression.d1 = { "A": "Auron", "B": "Braska", "C": "Crusaders" }
d2 = { "C": "Cid", "D": "Dona" }
d3 = {**d1, **d2}print(d3)
# {'A': 'Auron', 'B': 'Braska', 'C': 'Cid', 'D': 'Dona'}

Using the (+) Operator

If you are still working in Python 2.7, then using the plus sign to combine items from the two dictionaries produces a very easy-to-read single expression solution. However, this will not work in Python 3.d1 = { "A": "Auron", "B": "Braska", "C": "Crusaders" }
d2 = { "C": "Cid", "D": "Dona" }
d3 = dict(d1.items(), d2.items())print(d3)
# {'A': 'Auron', 'B': 'Braska', 'C': 'Cid', 'D': 'Dona'}

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe