Skip to content
Related Articles

Related Articles

Python | Flatten given list of dictionaries

View Discussion
Improve Article
Save Article
  • Last Updated : 12 Jan, 2022
View Discussion
Improve Article
Save Article

Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries.

Given below are a few methods to solve the given task.

Method #1: Using Naive Method

Python3




# Python code to demonstrate
# to flatten list of dictionaries
  
# Initialising dictionary
ini_dict = [{'a':1}, {'b':2}, {'c':3}]
  
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
  
# code to flatten list of dictionary
res = {}
for d in ini_dict:
    res.update(d)
      
# printing result
print ("result", str(res))

Output:

initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'b': 2, 'a': 1, 'c': 3}

 

Method #2: Using dict comprehension

Python3




# Python code to demonstrate
# to flatten list of dictionaries
  
# Initialising dictionary
ini_dict = [{'a':1}, {'b':2}, {'c':3}]
  
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
  
# code to flatten list of dictionary
res = {k: v for d in ini_dict for k, v in d.items()}
      
# printing result
print ("result", str(res))

Output:

initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'a': 1, 'c': 3, 'b': 2}

 
Method #3: Using reduce

Python3




# Python code to demonstrate
# to flatten list of dictionaries
from functools import reduce 
  
# Initialising dictionary
ini_dict = [{'a':1}, {'b':2}, {'c':3}]
  
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
  
# code to flatten list of dictionary
res = reduce(lambda d, src: d.update(src) or d, ini_dict, {})
      
# printing result
print ("result", str(res))

Output:

initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result {'a': 1, 'c': 3, 'b': 2}

 
Method #4: Using collections.ChainMap

Python3




# Python code to demonstrate
# to flatten list of 
# dictionaries
  
from collections import ChainMap
  
# Initialising dictionary
ini_dict = [{'a':1}, {'b':2}, {'c':3}]
  
# printing initial dictionary
print ("initial dictionary", str(ini_dict))
  
# code to flatten list of dictionary
res = ChainMap(*ini_dict)
      
# printing result
print ("result", str(res))

Output:

initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result ChainMap({'a': 1}, {'b': 2}, {'c': 3})

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!