Python | Flatten given list of dictionaries
Last Updated :
21 Apr, 2023
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
ini_dict = [{ 'a' : 1 }, { 'b' : 2 }, { 'c' : 3 }]
print ( "initial dictionary" , str (ini_dict))
res = {}
for d in ini_dict:
res.update(d)
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
ini_dict = [{ 'a' : 1 }, { 'b' : 2 }, { 'c' : 3 }]
print ( "initial dictionary" , str (ini_dict))
res = {k: v for d in ini_dict for k, v in d.items()}
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
from functools import reduce
ini_dict = [{ 'a' : 1 }, { 'b' : 2 }, { 'c' : 3 }]
print ( "initial dictionary" , str (ini_dict))
res = reduce ( lambda d, src: d.update(src) or d, ini_dict, {})
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
from collections import ChainMap
ini_dict = [{ 'a' : 1 }, { 'b' : 2 }, { 'c' : 3 }]
print ( "initial dictionary" , str (ini_dict))
res = ChainMap( * ini_dict)
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
ini_dict = [{ 'a' : 1 }, { 'b' : 2 }, { 'c' : 3 }]
def flatten_dict(dict_list):
if not dict_list:
return {}
else :
return { * * dict_list[ 0 ], * * flatten_dict(dict_list[ 1 :])}
flattened_dict = flatten_dict(ini_dict)
print ( "Result: " + str (flattened_dict))
|
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
ini_dict = [{ 'a' : 1 }, { 'b' : 2 }, { 'c' : 3 }]
print ( "Initial dictionary:" , ini_dict)
tuple_list = [(k, v) for d in ini_dict for k, v in d.items()]
res = dict (tuple_list)
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.
Please Login to comment...