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

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

    You can use a defaultdict to hold lists, and then just append the values to them. This approach easily extends to an arbitrary number of dictionaries.

    from collections import defaultdict
    
    dd = defaultdict(list)
    
    dics = [dic1, dic2]
    for dic in dics:
        for key, val in dic.iteritems():  # .items() in Python 3.
            dd[key].append(val)
    
    >>> dict(dd)
    {'first': [1, 9], 'fourth': [3], 'second': [4, 5], 'third': [8]}
    

    All of the keys with a single value are still held within a list, which is probably the best way to go. You could, however, change anything of length one into the actual value, e.g.

    for key, val in dd.iteritems():  # .items() in Python 3.
        if len(val) == 1
            dd[key] = val[0]
    

提交回复
热议问题