Python | Flatten given list of dictionaries
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
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
Python3
# Python code to demonstrate# to flatten list of dictionaries# Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]# printing initial dictionaryprint ("initial dictionary", str(ini_dict))# code to flatten list of dictionaryres = {}for d in ini_dict: res.update(d) # printing resultprint ("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 dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]# printing initial dictionaryprint ("initial dictionary", str(ini_dict))# code to flatten list of dictionaryres = {k: v for d in ini_dict for k, v in d.items()} # printing resultprint ("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 dictionariesfrom functools import reduce# Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]# printing initial dictionaryprint ("initial dictionary", str(ini_dict))# code to flatten list of dictionaryres = reduce(lambda d, src: d.update(src) or d, ini_dict, {}) # printing resultprint ("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# dictionariesfrom collections import ChainMap# Initialising dictionaryini_dict = [{'a':1}, {'b':2}, {'c':3}]# printing initial dictionaryprint ("initial dictionary", str(ini_dict))# code to flatten list of dictionaryres = ChainMap(*ini_dict) # printing resultprint ("result", str(res)) |
Output:
initial dictionary [{'a': 1}, {'b': 2}, {'c': 3}]
result ChainMap({'a': 1}, {'b': 2}, {'c': 3})


