Flatten a list of dictionaries

In this article we shall see how to flatten a list of dictionaries. This can be done by the following two ways.

  1. Traditional approach
  2. Dictionary comprehension

If you are a beginner the traditional approach will suit you. Dictionary comprehension method is suitable for intermediate programmers.

Note: Dictionary comprehension is not difficult but flattening a list of dictionaries using dictionary comprehension is a bit complex.

Let us get started. Consider the following list of dictionaries.

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

We will be flattening this list of dictionaries.

What is flattening a list of dictionaries?

Flattening a list of dictionaries is nothing but combining a list of dictionaries to a single dictionary. The final output is a single dictionary containing all the keys and values from the individual dictionaries.

Let us see how to do this beginning with the traditional approach.

Traditional approach

In the traditional approach we will iterate the list to get the dictionaries one by one and then the we will get the key and value from items() method.

Calling an items() method on a dictionary will give us a dict_items iterator object. The dict_items iterator object will have key, value pairs of dictionary as a tuple.

This is what happens when you call items() method on a dictionary.

{'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

We can get these values by tuple unpacking and create or add this key-value pair to the dictionary. This is how we can flatten a list of dictionaries using the traditional approach.

new_dict = {}
data = [{'a': 1}, {'b': 2}, {'c': 3, 'd': 4}]
for dicts in data:
    for key, value in dicts.items():
        new_dict[key] = value

print(new_dict)

The output of the above code is,

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

As you can see the list of dictionaries is combined to a single dictionary.

Dictionary comprehension

The dictionary comprehension approach is more of a one-liner approach. The above code can be converted to a single line of code if dictionary comprehension is used to flatten the list of dictionaries.

The code to perform a dictionary comprehension is,

data = [{'a': 1}, {'b': 2}, {'c': 3, 'd': 4}]
new_dict = {key: value for dicts in data for key, value in dicts.items()}
print(new_dict)

The output of this code is,

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Conclusion

Hope this article is helpful. If you have any queries leave them in the comments below.

Happy coding!