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

前端 未结 8 2304
广开言路
广开言路 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:44

    Using set and dictionary comprehension

    L = [d1, d2]
    dups = set(d1.keys() & d2.keys())
    d = {k: [L[0][k], L[1][k]] if k in dups else i[k] for i in L for k in i}
    
    {'first': [1, 9], 'second': [4, 5], 'third': 8, 'fourth': 3}
    

提交回复
热议问题