Merge two dictionaries and keep the values for duplicate keys in Python

前端 未结 8 2300
广开言路
广开言路 2021-02-08 19:16

Let\'s suppose that I have two dictionaries:

dic1 =  { \"first\":1, \"second\":4, \"third\":8} 
dic2 =  { \"first\":9, \"second\":5, \"fourth\":3}
相关标签:
8条回答
  • 2021-02-08 20:00

    Given:

    dic1 =  { "first":1, "second":4, "third":8} 
    dic2 =  { "first":9, "second":5, "fourth":3}
    

    You can use .setdefault:

    dic_new={}
    for k,v in list(dic1.items())+list(dic2.items()):
        dic_new.setdefault(k, []).append(v)
    else:
        dic_new={k:v if len(v)>1 else v[0] for k,v in dic_new.items()}  
    
    >>> dic_new
    {'first': [1, 9], 'second': [4, 5], 'third': 8, 'fourth': 3}
    

    This produces the output in question. I think that flattening the single elements lists to a different object type is an unnecessary complexity.


    With the edit, this produces the desired result:

    dic_new={}
    for k,v in list(dic1.items())+list(dic2.items()):
        dic_new.setdefault(k, []).append(v)
    
    >>> dic_new
    {'first': [1, 9], 'second': [4, 5], 'third': [8], 'fourth': [3]}
    
    0 讨论(0)
  • 2021-02-08 20:08

    Create a new dictionary dic having for keys the keys of dic1 and dic2 and value an empty list, then iterate over dic1 and dic2 appending values to dic:

    dic1 =  { "first":1, "second":4, "third":8} 
    dic2 =  { "first":9, "second":5, "fourth":3}
    
    dic = {key:[] for key in list(dic1.keys()) + list(dic2.keys())}
    
    for key in dic1.keys():
        dic[key].append(dic1[key])
    
    for key in dic2.keys():
        dic[key].append(dic2[key])
    
    0 讨论(0)
提交回复
热议问题