हमारे पास एक सूची है जिसके तत्व शब्दकोश हैं। हमें इसे फ्लैट करके एक ही शब्दकोश प्राप्त करना है जहां ये सभी सूची तत्व कुंजी-मान जोड़े के रूप में मौजूद हों।
for और update के साथ
हम एक खाली शब्दकोश लेते हैं और सूची से तत्वों को पढ़कर इसमें तत्व जोड़ते हैं। तत्वों का जोड़ update फ़ंक्शन का उपयोग करके किया जाता है।
उदाहरण
listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}]
# दी गई सरणी प्रिंट करें
print("Given array:\n",listA)
print("Type of Object:\n",type(listA))
res = {}
for x in listA:
res.update(x)
# परिणाम
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 फ़ंक्शन के साथ reduce फ़ंक्शन का भी उपयोग कर सकते हैं।
उदाहरण
from functools import reduce
listA = [{'Mon':2}, {'Tue':11}, {'Wed':3}]
# दी गई सरणी प्रिंट करें
print("Given array:\n",listA)
print("Type of Object:\n",type(listA))
# reduce और update का उपयोग करके
res = reduce(lambda d, src: d.update(src) or d, listA, {})
# परिणाम
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}]
# दी गई सरणी प्रिंट करें
print("Given array:\n",listA)
print("Type of Object:\n",type(listA))
# reduce और update का उपयोग करके
res = ChainMap(*listA)
# परिणाम
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: