dictionary - Union python dictioniaries with function on collision -


in python, there way merge dictionaries , on collision? i'm looking idiom equivalent 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

with dictionary comprehension.

>>> 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, [])) key in set( d1.keys() + d2.keys())} {'a': [42, 3], 'c': [4], 'b': [12, 2], 'd': [0]} 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -