解压缩Python中的字典列表 [英] Unpack list of dictionaries in Python
问题描述
根据此答案,在Python 3.5或更高版本中,可以合并两个词典x
和y
打开它们的包装:
According to this answer, in Python 3.5 or greater, it is possible to merge two dictionaries x
and y
by unpacking them:
z = {**x, **y}
是否可以解压缩各种字典?像
Is it possible to unpack a variadic list of dictionaries? Something like
def merge(*dicts):
return {***dicts} # this fails, of course. What should I use here?
例如,我希望
list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]
{***list_of_dicts} == {'a': 1, 'b': 2, 'c': 3, 'd': 4}
请注意,此问题与如何合并字典列表无关,因为上面的链接提供了对此的答案.这里的问题是:是否可以解压缩字典列表?如何解压缩字典列表?
Note that this question is not about how to merge lists of dictionaries since the link above provides an answer to this. The question here is: is it possible, and how, to unpack lists of dictionaries?
As stated in the comments, this question is very similar to this one. However, unpacking a list of dictionaries is different from simply merging them. Supposing that there was an operator ***
designed to unpack lists of dictionaries, and given
def print_values(a, b, c, d):
print('a =', a)
print('b =', b)
print('c =', c)
print('d =', d)
list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3}, {'d': 4}]
有可能写
print_values(***list_of_dicts)
代替
print_values(**merge(list_of_dicts))
推荐答案
另一个解决方案是使用collections.ChainMap
Another solution is using collections.ChainMap
from collections import ChainMap
dict(ChainMap(*list_of_dicts[::-1]))
Out[88]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
这篇关于解压缩Python中的字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!