Combining two dictionaries into one with the same keys?

前端 未结 7 1771
眼角桃花
眼角桃花 2020-12-06 03:35

I\'ve looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{\'A\': 25 ,          


        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 04:08

    I just needed to combine an unknown number dictionaries and after seeing answers to this question came up with more universal solutions:

    1) dictionaries of values:

    dic1 = {'A': 1, 'B': 1, 'C': 1}
    dic2 = {'A': 2, 'B': 2, 'C': 2}
    dic3 = {'D': 3, 'E': 3, 'F': 3}
    
    def combineDictVal(*args):
        result = {}
        for dic in args:
            for key in (result.viewkeys() | dic.keys()):
                if key in dic:
                    result.setdefault(key, []).append(dic[key])
        return result
    
    print combineDictVal(dic1, dic2, dic3)
    

    Result: {'A': [1, 2], 'C': [1, 2], 'B': [1, 2], 'E': [3], 'D': [3], 'F': [3]}

    2) dictionaries of lists (difference is in append/extend*):

    dic1 = {'A': [1, 2], 'B': [1, 2], 'C': [1, 2]}
    dic2 = {'A': [3, 4], 'B': [3, 4], 'C': [3, 4]}
    dic3 = {'D': [5, 6], 'E': [5, 6], 'F': [5, 6]}
    
    def combineDictList(*args):
        result = {}
        for dic in args:
            for key in (result.viewkeys() | dic.keys()):
                if key in dic:
                    result.setdefault(key, []).extend(dic[key])
        return result
    
    print combineDictList(dic1, dic2, dic3)
    

    Result: {'A': [1, 2, 3, 4], 'C': [1, 2, 3, 4], 'B': [1, 2, 3, 4], 'E': [5, 6], 'D': [5, 6], 'F': [5, 6]}

    3) Universal for int / lists:

    dic1 = {'A': 1, 'B': 1, 'C': [1, 1]}
    dic2 = {'A': 2, 'B': [2, 2], 'C': 2}
    dic3 = {'D': 3, 'E': 3, 'F': [3, 3]}
    
    def combineDict(*args):
        result = {}
        for dic in args:
            for key in (result.viewkeys() | dic.keys()):
                if key in dic:
                    if type(dic[key]) is list:
                        result.setdefault(key, []).extend(dic[key])
                    else:
                        result.setdefault(key, []).append(dic[key])
        return result
    
    print combineDict(dic1, dic2, dic3)
    

    Result:

    {'A': [1, 2], 'C': [1, 1, 2], 'B': [1, 2, 2], 'E': [3], 'D': [3], 'F': [3, 3]}
    

    These solutions are not the fastest possible, however they are clear and work just fine. Hope it will help someone.

提交回复
热议问题