Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge an arbitrary number of dictionaries of lists

How could dictionaries whose values are lists be merged in Python, so that all of the keys are moved into one dictionary, and all the elements of each list moved into a single list for each key?

For example, with these dictionaries:

x = {'a': [2], 'b': [2]}
y = {'b': [11], 'c': [11]}

... the result of the merging should be like this:

{'a': [2], 'b': [2, 11], 'c': [11]}

How could this be done with any number of dictionaries, not just two?

like image 989
shaziya Avatar asked Dec 05 '22 21:12

shaziya


1 Answers

for k, v in y.items():
    x.setdefault(k, []).extend(v)
like image 161
Daniel Roseman Avatar answered Dec 26 '22 10:12

Daniel Roseman