Combining lists of dictionaries based on list index

前端 未结 2 971
滥情空心
滥情空心 2021-01-15 19:51

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

相关标签:
2条回答
  • 2021-01-15 20:06

    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'}]
    
    0 讨论(0)
  • 2021-01-15 20:11

    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 zippped lists.

    0 讨论(0)
提交回复
热议问题