Python:有效地组合列表字典

时间:2021-03-15 00:05:29

标签: python python-3.x list-comprehension

我希望合并一个字典列表,每个字典都有一个键和值列表。我想输出不同的键,以及这些键的不同值。

a1 = {"lang": ["en"], "country": ["US"]}
a2 = {"lang": ["en"], "country": ["UK"]}
a3 = {"lang": ["fr"], "region": ["EU"]}
# many, many more...

full_list = [a1, a2, a3, ...]

output = {}
for f in full_list:
    for k,v in f.items():
        if k not in output:
            output[k] = set()
        output[k].update(set(v))
output = {k:list(v) for k,v in output.items()}

print(output)
>>> {"lang": ["en", "fr"], "country": ["US"], "region": ["EU"], ...}

这行得通,但它非常冗长而且有点慢。有没有一种快速的、pythonic 的方法来做到这一点?

0 个答案:

没有答案
相关问题