How to merge two dicts and combine common keys?

后端 未结 3 1202
执念已碎
执念已碎 2021-01-17 01:35

I would like to know how if there exists any python function to merge two dictionary and combine all values that have a common key.

I have found function to append t

3条回答
  •  萌比男神i
    2021-01-17 02:01

    A solution, without importing anything:

    # First initialize data, done correctly here.
    D1 = [{'k1': 'v01'},            {'k3': 'v03'}, {'k4': 'v04'}]
    D2 = [{'k1': 'v11'}, {'k2': 'v12'},            {'k4': 'v14'}]
    
    # Get all unique keys
    keys = {k for d in [*D1, *D2] for k in d}
    
    # Initialize an empty dict
    D3 = {x:[] for x in keys}
    
    # sort to maintain order
    D3 = dict(sorted(D3.items()))
    
    #Iterate and extend
    for x in [*D1, *D2]:
        for k,v in x.items():
            D3[k].append(v)
    
    # NOTE: I do not recommend you convert a dictionary into a list of records.
    # Nonetheless, here is how it would be done.
    # To convert to a list
    D3_list = [{k:v} for k,v in D3.items()]
    
    print(D3_list)
    
    # [{'k1': ['v01', 'v11']},
    #  {'k2': ['v12']},
    #  {'k3': ['v03']},
    #  {'k4': ['v04', 'v14']}]
    

提交回复
热议问题