Combining two dictionaries into one with the same keys?

前端 未结 7 1766
眼角桃花
眼角桃花 2020-12-06 03:35

I\'ve looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{\'A\': 25 ,          


        
7条回答
  •  眼角桃花
    2020-12-06 04:14

    This is a generic version. This can be used to create a dictionary with values as a list, even if the key is present in only one of them.

    dic1 = {'A': 25, 'B': 41, 'C': 32}
    dic2 = {'A': 21, 'B': 12, 'C': 62}
    result = {}
    for key in (dic1.keys() | dic2.keys()):
        if key in dic1: result.setdefault(key, []).append(dic1[key])
        if key in dic2: result.setdefault(key, []).append(dic2[key])
    
    print(result)
    

    Output

    {'A': [25, 21], 'C': [32, 62], 'B': [41, 12]}
    

    If you are using Python 2, for loop has to be changed like this:

    for key in (dic1.viewkeys() | dic2.keys()):
    

提交回复
热议问题