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