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

前端 未结 8 2486
广开言路
广开言路 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 19:58

    Solution for dict of lists (adapted from @dawg):

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

提交回复
热议问题