'Union python dictioniaries with function on collision
In Python, is there a way to merge dictionaries and do something on collision? I'm looking for an idiom equivalent to the unionWith function in Haskell: http://hackage.haskell.org/packages/archive/containers/0.5.0.0/doc/html/Data-Map-Lazy.html#v:unionWith
>>> unionWith(lambda x,y: x + y, {'a' : [42], 'b' : [12], c : [4]}, {'a' : [3], 'b' : [2], 'd' : [0]})
{'a' : [42,3], 'b' : [12,2], 'c' : [4], 'd': [0]}
Implementation based on @monkut's solution: https://github.com/cheecheeo/useful/commit/109885a27288ef53a3de2fa2b3a6e50075c5aecf#L1R18
Solution 1:[1]
def union_with(merge_func, x, y):
result = dict(x)
for key in y:
if key in result:
result[key] = merge_func(result[key], y[key])
else:
result[key] = y[key]
return result
>>> union_with(lambda x,y: x + y, {'a' : [42], 'b' : [12], 'c' : [4]}, {'a' : [3], 'b' : [2], 'd' : [0]})
{'a': [42, 3], 'c': [4], 'b': [12, 2], 'd': [0]}
Solution 2:[2]
my 5 cents
dict = {'a' : [42], 'b' : [12], 'c' : [4]}, {'a' : [3], 'b' : [2], 'd' : [0]}
keyset = set([k for d in dict for k in d.keys()])
union = {}
for d in dict:
for k in d.keys():
if k in union:
union[k].append(d[k])
else:
union[k]=[s[k]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | archlight |
