Ta có một danh sách các phần tử là dictionary. Ta cần làm phẳng nó để có một dictionary duy nhất nơi tất cả các phần tử danh sách hiện diện như các cặp key-value.
Với for và update
Ta lấy một dictionary rỗng và thêm phần tử vào bằng cách đọc từ danh sách. Việc thêm dùng hàm update.
Ví dụ
listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}] # in mảng cho trước print("Given array:\n",listA) print("Type of Object:\n",type(listA)) res = {} for x in listA: res.update(x) # Kết quả print("Flattened object:\n ", res) print("Type of flattened Object:\n",type(res))Đầu ra
Chạy mã trên cho kết quả sau:
('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', )Với reduce
Ta cũng có thể dùng hàm reduce cùng update để đọc phần tử từ danh sách và thêm vào dictionary rỗng.
Ví dụ
from functools import reduce listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}] # in mảng cho trước print("Given array:\n",listA) print("Type of Object:\n",type(listA)) # Sử dụng reduce và update res = reduce(lambda d, src: d.update(src) or d, listA, {}) # Kết quả print("Flattened object:\n ", res) print("Type of flattened Object:\n",type(res))Đầu ra
Chạy mã trên cho kết quả sau:
('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', )Với ChainMap
Hàm ChainMap sẽ đọc từng phần tử từ danh sách và tạo một đối tượng collection mới nhưng không phải dictionary.
Ví dụ
from collections import ChainMap listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}] # in mảng cho trước print("Given array:\n",listA) print("Type of Object:\n",type(listA)) # Sử dụng reduce và update res = ChainMap(*listA) # Kết quả print("Flattened object:\n ", res) print("Type of flattened Object:\n",type(res))Đầu ra
Chạy mã trên cho kết quả sau:
Given array: [{'Mon': 2}, {'Tue': 11}, {'Wed': 3}] Type of Object: Flattened object: ChainMap({'Mon': 2}, {'Tue': 11}, {'Wed': 3}) Type of flattened Object: