How to merge two dicts and combine common keys?

后端 未结 3 1180
执念已碎
执念已碎 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条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 02:17

    If you meant to use actual dicts, instead of lists of dicts, this is easier.

    D1 = dict(k1=1, k3=3, k4=4)
    D2 = dict(k1=11, k2=12, k4=14)
    

    There isn't a simple built-in function to do this, but the setdefault method is close. It tries to get the given key, but creates it if it doesn't exist.

    D3 = {}
    for k, v in D1.items() | D2.items():
        D3.setdefault(k, set()).add(v)
    

    And the result.

    {'k4': {4, 14}, 'k1': {1, 11}, 'k3': {3}, 'k2': {12}}
    

    This all assumes the order doesn't matter, just combining sets.

提交回复
热议问题