# Python >= 3.5:defmerge_dictionaries(a, b):return{**a,**b}# else:defmerge_dictionaries(a, b):
c = a.copy()# make a copy of a
c.update(b)# modify keys and values of a with the b onesreturn c
a ={'x':1,'y':2}
b ={'y':3,'z':4}print(merge_dictionaries(a, b))# {'y': 3, 'x': 1, 'z': 4}
dict1 ={'color':'blue','shape':'square'}
dict2 ={'color':'red','edges':4}
dict1.update(dict2)#if a key exists in both, it takes the value of the second dict# dict1 = {'color': 'red', 'shape': 'square', 'edges': 4}# dict2 is left unchanged
# Python 3.9
z = x | y
# Python 3.5
z ={**x,**y}# Python <= 3.4defmerge_two_dicts(x, y):
z = x.copy()# start with keys and values of x
z.update(y)# modifies z with keys and values of yreturn z
z = merge_two_dicts(x, y)
# Example usage:# Say you have the following dictionaries and want to merge dict_b into dict_a
dict_a ={"ABC":{"DE":{"F":"G"}}}
dict_b ={"ABC":{"DE":{"H":"I"},"JKL":"M"}}defmerge_nested_dictionaries(dict_a, dict_b, path=None):"""
recursive function for merging dict_b into dict_a
"""if path isNone:
path =[]for key in dict_b:if key in dict_a:ifisinstance(dict_a[key],dict)andisinstance(dict_b[key],dict):
merge_nested_dictionaries(dict_a[key], dict_b[key], path +[str(key)])# if the b dictionary matches the a dictionary from here on, skip adding itelif dict_a[key]== dict_b[key]:pass# if the same series of keys lead to different terminal values in# each dictionary, the dictionaries can't be merged unambiguouslyelse:raise Exception('Conflict at %s'%'.'.join(path +[str(key)]))# if the key isn't in a, add the rest of the b dictionary to a at this pointelse:
dict_a[key]= dict_b[key]return dict_a
# running:
merge_nested_dictionaries(dict_a, dict_b)# returns:{'ABC':{'DE':{'F':'G','H':'I'},'JKL':'M'}}
how to merge two dictionaries with same keys in python
from collections import defaultdict
d1 ={1:2,3:4}
d2 ={1:6,3:7}
dd = defaultdict(list)for d in(d1, d2):# you can list as many input dicts as you want herefor key, value in d.items():
dd[key].append(value)print(dd)
defmerge_dicts(dict1, dict2):"""Here's an example of a for-loop being used abusively."""return{**dict2,**{k:(v ifnot(k in dict2)else(v + dict2.get(k))ifisinstance(v,list)else merge_dicts(v, dict2.get(k)))ifisinstance(v,dict)else v for k, v in dict1.items()}}
For dictionaries x and y, their shallowly-merged dictionary z takes values from y, replacing those from x.
In Python 3.9.0or greater (released 17 October 2020, PEP-584, discussed here):
z = x | y
In Python 3.5or greater:
z ={**x,**y}
In Python 2,(or3.4or lower) write a function:defmerge_two_dicts(x, y):
z = x.copy()# start with keys and values of x
z.update(y)# modifies z with keys and values of yreturn z
and now:
z = merge_two_dicts(x, y)
# list_of_dictionaries contains a generic number of dictionaries# having the same type of keys (str, int etc.) and type of values
global_dict ={}for single_dict in list_of_dictionaries:
global_dict.update(single_dict)
yusuke_power ={"Yusuke Urameshi":"Spirit Gun"}
hiei_power ={"Hiei":"Jagan Eye"}
powers =dict()# Brute forcefor dictionary in(yusuke_power, hiei_power):for key, value in dictionary.items():
powers[key]= value
# Dictionary Comprehension
powers ={key: value for d in(yusuke_power, hiei_power)for key, value in d.items()}# Copy and update
powers = yusuke_power.copy()
powers.update(hiei_power)# Dictionary unpacking (Python 3.5+)
powers ={**yusuke_power,**hiei_power}# Backwards compatible function for any number of dictsdefmerge_dicts(*dicts:dict):
merged_dict =dict()for dictionary in dicts:
merge_dict.update(dictionary)return merged_dict
# (*) unpacking operator# for positional vs keyword argument, see "03 functions"# for packing, see "03 functions" # * can unpack iterables eg tuple, list, strings etc to its elements. # ** can only unpack dictionary# convert range til list
l1 =[range(5)]print(l1)#[range(0, 5)]
l =[*range(5)]# * unpacking operatorprint(l)#[0, 1, 2, 3, 4]# unpacking a collection
my_tuple =(1,2,3,4,5,6,7)
i1,*i2, i3, i4 = my_tuple # the middle part of the tuple gets unpacked into a list in i2print(i1)print(i2)print(i3)print(i4)# 1# [2, 3, 4, 5]# 6# 7# merge containers
my_tuple =(1,2,3)
my_list =[4,5,6]
merged_list =[*my_tuple,*my_list]print(merged_list)# [1, 2, 3, 4, 5, 6]
dict_a ={'a':1,'b':2}
dict_b ={'c':3,'d':4}
merged_dict ={**dict_a,**dict_b}print(merged_dict)# {'a': 1, 'b': 2, 'c': 3, 'd': 4}# unpacking arguments passed to function calls# Ex 1: unpack collections into func argumentsdeffoo(a, b,*args,**kwargs):print(a, end =' ')for arg in args:#args is unpacked into an iterable objectprint(arg, end =' ')for key in kwargs:print(key, kwargs[key], end =' ')
foo(1,2,3,4,5, six=6, seven=7)# 1 3 4 5 six 6 seven 7
values =(1,2,3,4,5)
mydict ={'eight':8,'nine':9}
foo(*values,**mydict)#NB! * unpacking operator, otherwise passing a tuple + dict#1 3 4 5 eight 8 nine 9 #NB! ** for dict, otherwise only get keys# Ex 2: matching parameters with unpacked argumentsdefmyFun(a, b, c):print("a:", a)print("b:", b)print("c:", c)# keys in dictionary must be the same as names of parameters
kwargs ={"a":"One","b":"Two","c":"Three"}#dictionary
myFun(**kwargs)# passing a dictionary into myFun() by unpacking it and pass individual key:value pair# a: One# b: Two# c: Three