Merging two dictionaries in Python

shekhar pandey
2 min readNov 20, 2019

--

We cover in this article to Merge two dictionaries in Python

Using dict.update() :
Syntax: dict.update([other])
It accepts an another dictionary or an Iterable object (collection of key value pairs) as argument. Then merges the contents of this passed dictionary or Iterable in the current dictionary.

Lets say we have two dictionaries , d1 and d2 as following:
d1 = {‘lucky_color’:’red’, ‘lucky_num’:7}
d2 = {‘lucky_day’:’Sunday’}

d1.update(d2)
print(‘d1: ‘, d1);
d1: {‘lucky_color’: ‘red’, ‘lucky_num’: 7, ‘lucky_day’: ‘Sunday’}

Note
Important point to notice is that, we didn’t get a new dictionary. The contents of dict d1 changed and now apart from its existing contents it has the contents of dict d2 also.

What if we want to merged the contents of 2 dictionaries to a new dictionary ? Let’s see how to do that.

Merge two or more Dictionaries using **kwargs

Using **kwargs we can send variable length key-value pairs to a function. When we apply ** to a dictionary, then it expands the contents in dictionary as a collection of key value pairs.

d1 = {‘lucky_color’:’red’, ‘lucky_num’:7}
d2 = {‘lucky_day’:’Sunday’, ‘lucky_num’: 9}

# Lets merge contents of d1 and d2 into a new dictionary d3
d3 = {**d1, **d2}
print(‘d3 :’, d3)
d3 : {‘lucky_color’: ‘red’, ‘lucky_num’: 9, ‘lucky_day’: ‘Sunday’}

Note:
d1 and d2 have one common key ‘lucky_num’, in dict d3, last value is retained (i.e previous value gets overridden)

How to retain all values of common keys

def mergeDict(dict1, dict2):
‘’’merge two dictonaries, keeping all values for common keys
‘’’
common_keys = set(d1.keys()) & set(d2.keys())
dict3 = {**dict1, **dict2}

for k in common_keys:
dict3[k] = [dict1[k], dict3[k]]

return dict3

d1 = {‘lucky_color’:’red’, ‘lucky_num’:7}
d2 = {‘lucky_day’:’Sunday’, ‘lucky_num’: 9}

d3 = mergeDict(d1, d2)
print(d3)
{‘lucky_color’: ‘red’, ‘lucky_num’: [7, 9], ‘lucky_day’: ‘Sunday’}

--

--

No responses yet