Open In App

Python | Flatten given list of dictionaries

Last Updated : 21 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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}

Time complexity of the given code is O(n), where n is the total number of key-value pairs in all the dictionaries within the input list ini_dict.
The space complexity of the code is O(n), as a new dictionary res is created to store the flattened key-value pairs, and it will have a maximum of n key-value pairs.

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}

The time complexity of the code is O(n), where n is the total number of key-value pairs in the input list of dictionaries.
The auxiliary space used by the code is O(n), where n is the total number of key-value pairs in the input list of dictionaries.

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})

Method #5: Using a recursive function

Base case: if the list is empty, return an empty dictionary
Recursive case: flatten the first dictionary in the list and the rest of the list

Python3




#initializing list of dictionaries
ini_dict = [{'a':1}, {'b':2}, {'c':3}]
def flatten_dict(dict_list):
#base case: if the list is empty, return an empty dictionary
  if not dict_list:
    return {}
#recursive case: flatten the first dictionary in the list and the rest of the list
  else:
    return {**dict_list[0], **flatten_dict(dict_list[1:])}
 
flattened_dict = flatten_dict(ini_dict)
print("Result: "+str(flattened_dict)) # Output: {'a': 1, 'b': 2, 'c': 3}
#This code is contributed by Edula Vinay Kumar Reddy


Output

Result: {'a': 1, 'b': 2, 'c': 3}

The time complexity of the recursive approach is O(n), where n is the number of dictionaries in the list. This is because the function processes each dictionary in the list once.

The space complexity of the recursive approach is also O(n), because the function creates a new dictionary for each level of recursion. The depth of the recursion is equal to the number of dictionaries in the list, so the function will create n dictionaries.

Method 6: Using list comprehension and the dict() constructor.

  • Initialize a list of dictionaries called ini_dict, where each dictionary contains a single key-value pair.
  • Print the ini_dict using the print() function.
  • Create a new list of tuples called tuple_list using list comprehension and dict() constructor, by iterating through each dictionary in ini_dict and then iterating through each key-value pair in that dictionary.
  • Use the dict() constructor to convert tuple_list to a dictionary called res.
  • Print the res dictionary using the print() function.

Python3




# Initialising dictionary
ini_dict = [{'a':1}, {'b':2}, {'c':3}]
 
# printing initial dictionary
print ("Initial dictionary:", ini_dict)
 
# flattening list of dictionaries using list comprehension and dict() constructor
tuple_list = [(k, v) for d in ini_dict for k, v in d.items()]
res = dict(tuple_list)
 
# printing result
print ("Flattened dictionary:", res)


Output

Initial dictionary: [{'a': 1}, {'b': 2}, {'c': 3}]
Flattened dictionary: {'a': 1, 'b': 2, 'c': 3}

Time complexity: O(n), where n is the total number of key-value pairs in all the dictionaries. 
Auxiliary space: O(n) as well, since we create a new list of tuples containing all the key-value pairs in the dictionaries.



Previous Article
Next Article

Similar Reads

Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Python - Distinct Flatten dictionaries
Sometimes, while working with dictionaries, we can have keys which in itself is a part of very complex nestings and we wish to extract all the keys and values of particular key nesting into a separate list. This kind of problem can have applications in many domains such as web development. Lets discuss certain ways in which this task can be perform
6 min read
Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted
7 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python - Convert List of Dictionaries to List of Lists
Sometimes, while working with Python data, we can have a problem in which we need to convert the list of dictionaries into a list of lists, this can be simplified by appending the keys just once if they are repetitive as mostly in records, this saves memory space. This type of problem can have applications in the web development domain. Let's discu
7 min read
Python - Convert list of dictionaries to Dictionary Value list
Given a list of dictionary, convert to dictionary with same key mapped with all values in as value list. Input : test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}] Output : {'Gfg': [6, 8], 'is': [9, 11], 'best': [10, 19]} Explanation : 6, 8 of "Gfg" mapped as value list, similarly every other. Input : test_list =
10 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Python - Convert List to List of dictionaries
Given list values and keys list, convert these values to key value pairs in form of list of dictionaries. Input : test_list = ["Gfg", 3, "is", 8], key_list = ["name", "id"] Output : [{'name': 'Gfg', 'id': 3}, {'name': 'is', 'id': 8}] Explanation : Values mapped by custom key, "name" -> "Gfg", "id" -> 3. Input : test_list = ["Gfg", 10], key_li
5 min read
Practice Tags :