Home >Backend Development >Python Tutorial >How Can I Merge Python Dictionaries with Duplicate Keys into Lists of Values?
In Python, dealing with multiple dictionaries can be challenging, especially when merging them becomes necessary. A common issue arises when dictionaries share duplicate keys, and the goal is to collect all values associated with these keys into a single list.
To handle this efficiently, a powerful Python tool called defaultdict from the collections module comes into play. It allows for creating a default value (in this case, an empty list) for any key that doesn't exist in the dictionary.
Consider the following example:
d1 = {1: 2, 3: 4} d2 = {1: 6, 3: 7}
To merge these dictionaries, collecting values from matching keys, we can use defaultdict as follows:
from collections import defaultdict dd = defaultdict(list) for d in (d1, d2): # loop through all input dictionaries for key, value in d.items(): dd[key].append(value) print(dd) # result: defaultdict(<type 'list'>, {1: [2, 6], 3: [4, 7]})
In this code:
This solution efficiently collects all values associated with matching keys from multiple dictionaries, providing a clean and versatile way to handle duplicate keys.
The above is the detailed content of How Can I Merge Python Dictionaries with Duplicate Keys into Lists of Values?. For more information, please follow other related articles on the PHP Chinese website!