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

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

    In general, I would say it's bad practice to cast the values of different keys as different object types. I would simply do something like:

    def merge_values(val1, val2):
        if val1 is None:
            return [val2]
        elif val2 is None:
            return [val1]
        else:
            return [val1, val2]
    dict3 = {
        key: merge_values(dic1.get(key), dic2.get(key))
        for key in set(dic1).union(dic2)
    }
    

提交回复
热议问题