python – How to merge multiple dicts with same key or different key?
python – How to merge multiple dicts with same key or different key?
Heres a general solution that will handle an arbitrary amount of dictionaries, with cases when keys are in only some of the dictionaries:
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 here
for key, value in d.items():
dd[key].append(value)
print(dd)
Shows:
defaultdict(<type list>, {1: [2, 6], 3: [4, 7]})
Also, to get your .attrib
, just change append(value)
to append(value.attrib)
assuming all keys are always present in all dicts:
ds = [d1, d2]
d = {}
for k in d1.iterkeys():
d[k] = tuple(d[k] for d in ds)
Note: In Python 3.x use below code:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
and if the dic contain numpy arrays:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = np.concatenate(list(d[k] for d in ds))
python – How to merge multiple dicts with same key or different key?
Here is one approach you can use which would work even if both dictonaries dont have same keys:
d1 = {a:test,b:btest,d:dreg}
d2 = {a:cool,b:main,c:clear}
d = {}
for key in set(d1.keys() + d2.keys()):
try:
d.setdefault(key,[]).append(d1[key])
except KeyError:
pass
try:
d.setdefault(key,[]).append(d2[key])
except KeyError:
pass
print d
This would generate below input:
{a: [test, cool], c: [clear], b: [btest, main], d: [dreg]}