Combining lists of dictionaries based on list index

前端 未结 2 972
滥情空心
滥情空心 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'}]
    

提交回复
热议问题