展平 Python 中给定的字典列表
我们有一个列表元素为字典的列表。我们需要将其展平,以获得一个包含所有这些列表元素作为键值对的单个字典。
使用 for 和 update
我们取一个空字典,通过从列表读取元素将元素添加到其中。元素的添加是使用 update 函数完成的。
示例
listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}]
# printing given arrays
print("Given array:\n",listA)
print("Type of Object:\n",type(listA))
res = {}
for x in listA:
res.update(x)
# Result
print("Flattened object:\n ", res)
print("Type of flattened Object:\n",type(res))输出
运行上述代码会给我们以下结果 −
('Given array:\n', [{'Mon': 2}, {'Tue': 11}, {'Wed': 3}])
('Type of Object:\n', )
('Flattened object:\n ', {'Wed': 3, 'Mon': 2, 'Tue': 11})
('Type of flattened Object:\n', )使用 reduce
我们还可以使用 reduce 函数和 update 函数从列表中读取元素并将其添加到空字典中。
示例
from functools import reduce
listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}]
# printing given arrays
print("Given array:\n",listA)
print("Type of Object:\n",type(listA))
# Using reduce and update
res = reduce(lambda d, src: d.update(src) or d, listA, {})
# Result
print("Flattened object:\n ", res)
print("Type of flattened Object:\n",type(res))输出
运行上述代码会给我们以下结果 −
('Given array:\n', [{'Mon': 2}, {'Tue': 11}, {'Wed': 3}])
('Type of Object:\n', )
('Flattened object:\n ', {'Wed': 3, 'Mon': 2, 'Tue': 11})
('Type of flattened Object:\n', )使用 ChainMap
ChainMap 函数将从列表中读取每个元素,并创建一个新的集合对象但不是字典。
示例
from collections import ChainMap
listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}]
# printing given arrays
print("Given array:\n",listA)
print("Type of Object:\n",type(listA))
# Using reduce and update
res = ChainMap(*listA)
# Result
print("Flattened object:\n ", res)
print("Type of flattened Object:\n",type(res))输出
运行上述代码会给我们以下结果 −
Given array:
[{'Mon': 2}, {'Tue': 11}, {'Wed': 3}]
Type of Object:
Flattened object:
ChainMap({'Mon': 2}, {'Tue': 11}, {'Wed': 3})
Type of flattened Object:
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP