Skip to content
Related Articles

Related Articles

Improve Article

Python | Flatten given list of dictionaries

  • Last Updated : 03 Apr, 2019

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Method #1: Using Naive Method






# 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 lit 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




# 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 lit 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




# 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 lit 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




# 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 lit 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 :