flatten list of dictionaries

How to Flatten List of Dictionaries in Python

Python allows you to create lists of dictionaries where each list element is a dictionary. Sometimes you have a list of dictionaries and you may want to convert it into a list of single dictionary, also known as flattening a list. In this article, we will look at the different ways to flatten list of dictionaries in Python.


How to Flatten List of Dictionaries in Python

Here are the different ways to flatten list of dictionaries in Python. Let us say you have the following list of dictionaries.

>>> d=[{'a':1,'b':2},{'c':3,'d':4}]


1. Using for loop

This is the most basic and fastest method to convert a list of dictionaries into a single dictionary. Here is an example

>>> c={}
>>> for i in d:
	for j,k in i.items():
		c[j]=k
    c=[c]
>>> c
[{'a': 1, 'c': 3, 'b': 2, 'd': 4}]

In the above code, we look through the dictionaries in the loop one by one. For each dictionary, we loop through its individual items. In each iteration, we store its key and value in a separate list, c, which is our flattened list.


2. Using iterools.chain

itertools is a useful python library that allows you to easily perform operations on iterable data structures like lists. You can use its chain function. Here is an example.

>>> from itertools import chain
>>> [dict(chain(*map(dict.items, i.values()))) for i in d]
>>> [{'a': 1, 'b': 2, 'c': 3, 'd': 4}]


3. Using List Comprehension

You can also use list comprehension to easily flaten list of dictionaries. This is similar to the loop we used in method 1.

>>> res = {k: v for i in d for k, v in i.items()}
>>> res
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

In this article, we have looked at the different methods to flatten list of dictionaries. You may use any method according to your convenience.

Also read:

How to Flatten List of Tuples in Python
How to Find & Delete Broken Symlinks in Linux
How to Remove Duplicates from List in Linux
How to Get Key from Value in Python Dictionary
How to Flatten List of Lists in Python

Leave a Reply

Your email address will not be published. Required fields are marked *