Home >Backend Development >Python Tutorial >How to Merge a List of Dictionaries into a Single Dictionary in Python?
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)
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()}
Or, for Python versions prior to 2.7:
result = dict(pair for d in L for pair in d.items())
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!