Open In App

# 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

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