Skip to main content
 首页 » 编程设计

python之具有碰撞功能的联合python字典

2025年05月04日17pander-it

在 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

请您参考如下方法:

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]}