Answer the question
In order to leave comments, you need to log in
How to merge dictionaries by combining values by key into a list?
There are many dictionaries:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
} z = x.update(y)
Answer the question
In order to leave comments, you need to log in
You can do this if you do not need to take into account the fact that the value of the source dictionaries may contain lists that cannot be combined into one:
def merge_dicts(*dicts):
result = {}
for d in dicts:
for k,v in d.items():
if k in result:
if not isinstance(result[k], list):
result[k], t = list(), result[k]
result[k].append(t)
result[k].append(v)
else:
result[k] = v
return result
z = merge_dicts(x, y)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question