Computer >> Computer tutorials >  >> Programming >> Python

How can we merge two Python dictionaries?


In Python 3.5+, you can use the ** operator to unpack a dictionary and combine multiple dictionaries using the following syntax:

a = {'foo': 125}
b = {'bar': "hello"}
c = {**a, **b}
print(c)

This will give the output:

{'foo': 125, 'bar': 'hello'}

This is not supported in older versions. You can however replace it using the following similar syntax:

a = {'foo': 125}
b = {'bar': "hello"}
c = dict(a, **b)
print(c)

This will give the output:

{'foo': 125, 'bar': 'hello'}

Another thing you can do is using copy and update functions to merge the dictionaries. For example,

def merge_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modify z with y's keys and values
return z

a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)

This will give the output:

{'foo': 125, 'bar': 'hello'}