How to merge dicts, collecting values from matching keys?
dictionary, merge, python
Solution
assuming all keys are always present in all dicts:
ds = [d1, d2]
d = {}
for k in d1.iterkeys():
d[k] = tuple(d[k] for d in ds)
Note: In Python 3.x use below code:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
and if the dic contain numpy arrays:
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = np.concatenate(list(d[k] for d in ds))
Problem
I have multiple dicts (or sequences of key-value pairs) like this: ``` d1 = {key1: x1, key2: y1} d2 = {key1: x2, key2: y2} ``` How can I efficiently get a result like this, as a new dict? ``` d = {key1: (x1, x2), key2: (y1, y2)} ``` See also: How can one make a dictionary with duplicate keys in Python?.