We have a list whose elements are dictionaries. We need to flatten it to get a single dictionary where all these list elements are present as key-value pairs.
With for and update
We take an empty dictionary and add elements to it by reading the elements from the list. The addition of elements is done using the update function.
Example
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))
Output
Running the above code gives us the following result −
('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', )
With reduce
We can also use the reduce function along with update function to read the elements from the list and add it to the empty dictionary.
Example
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))
Output
Running the above code gives us the following result −
('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', )
With ChainMap
The ChainMap function will read each element from the list and create a new collection object but not a dictionary.
Example
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))
Output
Running the above code gives us the following result −
Given array: [{'Mon': 2}, {'Tue': 11}, {'Wed': 3}] Type of Object: Flattened object: ChainMap({'Mon': 2}, {'Tue': 11}, {'Wed': 3}) Type of flattened Object: