Combining two dictionaries into one with the same keys?

前端 未结 7 1775
眼角桃花
眼角桃花 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条回答
  •  不知归路
    2020-12-06 04:08

    This is one way, using defaultdict:

    # the setup
    >>> from collections import defaultdict
    >>> dict1 = {'A': 25, 'B': 41, 'C': 32}
    >>> dict2 = {'A': 21, 'B': 12, 'C': 62}
    
    # the preperation
    >>> dicts = [dict1, dict2]
    >>> final = defaultdict(list)
    
    # the logic
    >>> for k, v in ((k, v) for d in dicts for k, v in d.iteritems()):
        final[k].append(v)
    
    # the result
    >>> final 
    defaultdict(, {'A': [25, 21], 'C': [32, 62], 'B': [41, 12]})
    

提交回复
热议问题