根据列表索引组合字典列表


问题内容

我觉得这个问题以前必须已经问过,但是在Stack Overflow上找不到。

有没有一种方法可以根据列表索引优雅地组合多个词典列表?见下文:

list_1 = [{'hello': 'world'}, {'foo': 'test'}]
list_2 = [{'a': 'b'}, {'c': 'd'}]
result = [{'hello': 'world', 'a': 'b'},
          {'foo': 'test', 'c': 'd'}]

我了解我可以在技术上使用for循环,例如:

list_3 = []
for i in range(len(list_1)):
    list_3.append({**list_1[i],**list_2[i]})

有没有办法用列表理解做到这一点?如果我涉及两个以上的列表,或者不知道词典列表的数量,该怎么办?


问题答案:

这将做您想要的:

result = [{**x, **y} for x, y in zip(list_1, list_2)]

# [{'a': 'b', 'hello': 'world'}, {'c': 'd', 'foo': 'test'}]

有关语法的说明,请参见PEP 448**

对于通用解决方案:

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'}]