Merge dictionaries without overwriting values

后端 未结 3 383
既然无缘
既然无缘 2021-01-22 00:42

it seems a simple task:

I am trying to merge 2 dictionaries without overwriting the values but APPENDING.

a = {1: [(1,1)],2: [(2,2),(3,3)],3: [(4,4)]}          


        
3条回答
  •  无人及你
    2021-01-22 01:35

    If you want a third dictionary that is the combined one I would use the collection.defaultdict

    from collections import defaultdict
    from itertools import chain
    all = defaultdict(list)
    for k,v in chain(a.iteritems(), b.iteritems()):
        all[k].extend(v)
    

    outputs

    defaultdict(, {1: [(1, 1)], 2: [(2, 2), (3, 3)], 3: [(4, 4), (5, 5)], 4: [(6, 6)]})
    

提交回复
热议问题