How to Merge a List of Dictionaries into a Single Dictionary in Python?

Susan Sarandon
Release: 2024-11-09 21:55:02
Original
257 people have browsed it

How to Merge a List of Dictionaries into a Single Dictionary in Python?

Merging a List of Dictionaries into a Single Dictionary

To combine multiple dictionaries into a single comprehensive one, programmers often encounter the challenge of merging these dictionaries while maintaining unique keys. Here's a solution to this common problem:

For an input list of dictionaries, such as [{'a': 1}, {'b': 2}, {'c': 1}, {'d': 2}], the goal is to obtain a single consolidated dictionary: {'a': 1, 'b': 2, 'c': 1, 'd': 2}.

To achieve this, we employ a straightforward iteration approach:

result = {}
for d in L:
    result.update(d)
Copy after login

This approach iterates over each dictionary in the list, merging its key-value pairs into the result dictionary using the update() method. The result is a comprehensive dictionary with all the unique keys and associated values from the input list of dictionaries.

Alternatively, one can employ a comprehension-based approach in Python 2.7 or later:

result = {k: v for d in L for k, v in d.items()}
Copy after login

Or, for Python versions prior to 2.7:

result = dict(pair for d in L for pair in d.items())
Copy after login

These methods also produce the desired merged dictionary, demonstrating the versatility of Python's data manipulation capabilities.

The above is the detailed content of How to Merge a List of Dictionaries into a Single Dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template