我怎样才能打开这样的字典列表..
[{'a':1}, {'b':2}, {'c':1}, {'d':2}]
…变成这样的单个字典:
{'a':1, 'b':2, 'c':1, 'd':2}
这适用于任何长度的字典:
>>> 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())