Python: Reducing a List in a Dictionary
Question: I'm hoping this will be easy. I have a dictionary:

    
    
     { 
          'key1': 'value1',
          'key2': 'value2',
          'key3': 'value3'
     },
     { 
          'key1': 'value4',
          'key2': 'value5',
          'key3': 'value6'
     },
    

How can I reduce this to be the following:

    
    
     { 'key1': ['value1', 'value4'], 'key2': ['value2', 'value5'], 'key3': ['value3', 'value6'] }
    

Many thanks!


Answer: Like this:

    
    
    from collections import defaultdict
    
    d1 = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' } 
    d2 = { 'key1': 'value4', 'key2': 'value5', 'key3': 'value6' }
    
    dout = defaultdict(list)
    for item in d1:
        dout[item].append(d1[item])
    for item in d2:
        dout[item].append(d2[item])
    print dout
    

