เรามีรายการที่มีองค์ประกอบเป็นพจนานุกรม เราจำเป็นต้องทำให้เรียบเพื่อให้ได้พจนานุกรมเดียวที่มีองค์ประกอบรายการทั้งหมดนี้เป็นคู่คีย์-ค่า
พร้อมสำหรับและอัปเดต
เราใช้พจนานุกรมเปล่าและเพิ่มองค์ประกอบเข้าไปโดยการอ่านองค์ประกอบจากรายการ การเพิ่มองค์ประกอบทำได้โดยใช้ฟังก์ชันอัปเดต
ตัวอย่าง
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', ) พร้อมลด
นอกจากนี้เรายังสามารถใช้ฟังก์ชันลดพร้อมกับฟังก์ชันอัปเดตเพื่ออ่านองค์ประกอบจากรายการและเพิ่มลงในพจนานุกรมเปล่าได้
ตัวอย่าง
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: