我们有一个列表,其元素为字典。我们需要将其展平以得到单个字典,其中所有这些列表元素都以键值对的形式出现。
我们采用一个空字典,并通过从列表中读取元素来向其中添加元素。元素的添加是使用更新功能完成的。
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函数与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函数将从列表中读取每个元素,并创建一个新的集合对象,但不创建字典。
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: