How to merge multiple dicts with same key?

前端 未结 14 2392
别跟我提以往
别跟我提以往 2020-11-22 13:12

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1}  
d2 = {key1: x2, key2: y2}  

I want the result to be a new di

相关标签:
14条回答
  • 2020-11-22 14:00

    Here is one approach you can use which would work even if both dictonaries don't have same keys:

    d1 = {'a':'test','b':'btest','d':'dreg'}
    d2 = {'a':'cool','b':'main','c':'clear'}
    
    d = {}
    
    for key in set(d1.keys() + d2.keys()):
        try:
            d.setdefault(key,[]).append(d1[key])        
        except KeyError:
            pass
    
        try:
            d.setdefault(key,[]).append(d2[key])          
        except KeyError:
            pass
    
    print d
    

    This would generate below input:

    {'a': ['test', 'cool'], 'c': ['clear'], 'b': ['btest', 'main'], 'd': ['dreg']}
    
    0 讨论(0)
  • 2020-11-22 14:01

    Python 3.x Update

    From Eli Bendersky answer:

    Python 3 removed dict.iteritems use dict.items instead. See Python wiki: https://wiki.python.org/moin/Python3.0

    from collections import defaultdict
    
    dd = defaultdict(list)
    
    for d in (d1, d2):
        for key, value in d.items():
            dd[key].append(value)
    
    0 讨论(0)
提交回复
热议问题