pythonpython-3.xalibaba-cloudalibaba-cloud-ecs

How to merge two or more dict into one dict with retaining multiple values of same key as list?


I have two or more dictionary, I like to merge it as one with retaining multiple values of the same key as list. I would not able to share the original code, so please help me with the following example.

Input:

a= {'a':1, 'b': 2}
b= {'aa':4, 'b': 6}
c= {'aa':3, 'c': 8}

Output:

c= {'a':1,'aa':[3,4],'b': [2,6], 'c': 8}

Solution

  • I suggest you read up on the defaultdict: it lets you provide a factory method that initializes missing keys, i.e. if a key is looked up but not found, it creates a value by calling factory_method(missing_key). See this example, it might make things clearer:

    from collections import defaultdict
    
    a = {'a': 1, 'b': 2}
    b = {'aa': 4, 'b': 6}
    c = {'aa': 3, 'c': 8}
    
    stuff = [a, b, c]
    # our factory method is the list-constructor `list`,
    # so whenever we look up a value that doesn't exist, a list is created;
    # we can always be sure that we have list-values
    store = defaultdict(list)
    
    for s in stuff:
        for k, v in s.items():
            # since we know that our value is always a list, we can safely append
            store[k].append(v)
    
    print(store)
    

    This has the "downside" of creating one-element lists for single occurences of values, but maybe you are able to work around that.