展平 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:

更新日期: 04-6月-2020

852 次觀看

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.