如何将字典列表合并为一个字典?

如何将字典列表合并为一个字典?

问题描述:

我该如何列出这样的字典.

How can I turn a list of dicts like this..

[{'a':1}, {'b':2}, {'c':1}, {'d':2}]

...变成这样的单个字典:

...into a single dict like this:

{'a':1, 'b':2, 'c':1, 'd':2}

此方法适用于任何长度的字典:

This works for dictionaries of any length:

>>> result = {}
>>> for d in L:
...    result.update(d)
... 
>>> result
{'a':1,'c':1,'b':2,'d':2}

作为理解:

# Python >= 2.7
{k: v for d in L for k, v in d.items()}

# Python < 2.7
dict(pair for d in L for pair in d.items())