1

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!

KingFish
  • 8,773
  • 12
  • 53
  • 81
  • 2
    possible duplicate of [merging Python dictionaries](http://stackoverflow.com/questions/2365921/merging-python-dictionaries) – Adam Apr 04 '14 at 01:09

4 Answers4

3

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
carlosdc
  • 12,022
  • 4
  • 45
  • 62
3

This works for the case of two dicts with the same keys:

a = { 
  'key1': 'value1',
  'key2': 'value2',
  'key3': 'value3'
}

b = { 
'key1': 'value4',
'key2': 'value5',
'key3': 'value6'
}

c= {k: [a[k], b[k]] for k in a.keys()}
wils484
  • 275
  • 1
  • 3
  • 14
0

Like so -

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

d = {}
for k,v in [(k,v) for item in vals for k,v in item.items()]:
    d[k] = d[k] + [v] if d.get(k) else [v]


#>>> d
#{'key3': ['value3', 'value6'], 'key2': ['value2', 'value5'], 'key1': ['value1', 'value4']}
Scott
  • 1,648
  • 13
  • 21
0

Convert a list of dicts to a dict with list of values

from itertools import chain
result = {}
data = [
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
    {'key1': 'value4', 'key2': 'value5', 'key3': 'value6'},
]

list_of_tuples = chain(*[x.items() for x in data])
for k, v in list_of_tuples:
  result.setdefault(k, []).append(v)

print(result)

Output:

> python app.py
{'key3': ['value3', 'value6'], 'key2': ['value2', 'value5'], 'key1': ['value1', 'value4']}
Wiesom
  • 99
  • 2