I feel like this question must have been asked previously but could not find it on Stack Overflow.
Is there a way to elegantly combine multiple lists of dictionaries
This will do what you want:
result = [{**x, **y} for x, y in zip(list_1, list_2)]
# [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]
See PEP 448 for an explanation of **
syntax.
For a generalised solution:
list_1=[{'hello':'world'},{'foo':'test'}]
list_2=[{'a':'b'},{'c':'d'}]
list_3=[{'e':'f'},{'g':'h'}]
lists = [list_1, list_2, list_3]
def merge_dicts(*dict_args):
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
result = [merge_dicts(*i) for i in zip(*lists)]
# [{'a': 'b', 'e': 'f', 'hello': 'world'}, {'c': 'd', 'foo': 'test', 'g': 'h'}]
For a generalizable solution, in Python 3, you could do something like:
In [14]: from operator import or_
In [15]: from functools import reduce
In [16]: list_of_lists = [list_1, list_2]
In [17]: [dict(reduce(or_, map(dict.items, ds))) for ds in zip(*list_of_lists)]
Out[17]: [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]
In Python 2, no need to import reduce
, since it is already in the global namespace, but you will need to use dict.viewitems
instead of dict.items
:
[dict(reduce(or_, map(dict.viewitems, ds))) for ds in zip(*list_of_lists)]
Note the only real problem with your solution that I can see is that it uses for i in range(...)
, when you should just loop over the zip
pped lists.