2

在 Python 中,有没有办法合并字典并在碰撞时做些什么?我正在寻找与 Haskell 中的 unionWith 函数等效的成语: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]}

基于@monkut的解决方案实现:https ://github.com/cheecheeo/useful/commit/109885a27288ef53a3de2fa2b3a6e50075c5aecf#L1R18

4

3 回答 3

4
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]}
于 2012-06-05T05:56:03.437 回答
2

用字典理解。

>>> def merge_func(x,y):
...    return x + y
...
>>>
>>> d1 = {'a' : [42], 'b' : [12], 'c' : [4]}
>>> d2 = {'a' : [3], 'b' : [2], 'd' : [0]}
>>> { key: merge_func(d1.get(key, []), d2.get(key, [])) for key in set( d1.keys() + d2.keys())}
{'a': [42, 3], 'c': [4], 'b': [12, 2], 'd': [0]}
于 2012-06-05T06:10:00.717 回答
1

我的 5 美分

 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]]
于 2012-06-05T07:58:32.810 回答