Categories
Python Answers

How to merge a list of dicts into a single dict with Python?

Spread the love

Sometimes, we want to merge a list of dicts into a single dict with Python.

In this article, we’ll look at how to merge a list of dicts into a single dict with Python.

How to merge a list of dicts into a single dict with Python?

To merge a list of dicts into a single dict with Python, we can use reduce function from the functools module.

For instance, we write:

from functools import reduce

list_of_dicts = [{'a': 1}, {'b': 2}, {'c': 1}, {'d': 2}]
d = reduce(lambda a, b: dict(a, **b), list_of_dicts)
print(d)

We call reduce with a function that merges dictionary a with the entries in b and return it.

a and b are both entries in list_of_dicts.

The merging is done by unpacking the entries in b and putting it into a new dictionary with a and returning it.

Therefore, d is {'a': 1, 'b': 2, 'c': 1, 'd': 2}.

Conclusion

To merge a list of dicts into a single dict with Python, we can use reduce function from the functools module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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