2012-06-05 47 views
1

在Python中,是否有合併字典並對碰撞進行操作的方法?我在尋找成語相當於unionWith功能在Haskell的:根據@ monkut的解決方案http://hackage.haskell.org/packages/archive/containers/0.5.0.0/doc/html/Data-Map-Lazy.html#v:unionWith具有碰撞功能的聯合python字典

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

實現:https://github.com/cheecheeo/useful/commit/109885a27288ef53a3de2fa2b3a6e50075c5aecf#L1R18

回答

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

爲什麼你需要一個'defaultdict'在這裏? –

+0

defaultdict(列表)用於避免關鍵錯誤。 – monkut

+0

哦,對,理解。謝謝! –

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

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