When working with multiple dictionaries containing overlapping keys, it becomes necessary to efficiently merge them while collecting values associated with those keys. This article explores a solution to combine and collect values from matching keys within a collection of dictionaries.
Given several dictionaries like:
d1 = {key1: x1, key2: y1} d2 = {key1: x2, key2: y2}
The goal is to obtain a merged result as a new dictionary, where each key holds a tuple of values from the original dictionaries:
d = {key1: (x1, x2), key2: (y1, y2)}
The solution utilizes the collections.defaultdict to create a dictionary with default values as mutable lists. This allows the accumulation of values for each key:
from collections import defaultdict d1 = {1: 2, 3: 4} d2 = {1: 6, 3: 7} dd = defaultdict(list) for d in (d1, d2): # Input dictionaries can be iterated over here for key, value in d.items(): dd[key].append(value)
The final merged dictionary dd contains each key mapped to a list of values from the input dictionaries.
The above is the detailed content of How Can I Efficiently Merge Dictionaries with Duplicate Keys and Collect Their Values?. For more information, please follow other related articles on the PHP Chinese website!