KingFish
KingFish

Reputation: 9153

Python: Reducing a List in a Dictionary

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!

Upvotes: 1

Views: 192

Answers (4)

Wiesom
Wiesom

Reputation: 99

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']}

Upvotes: 0

Scott
Scott

Reputation: 1688

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']}

Upvotes: 0

wils484
wils484

Reputation: 275

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()}

Upvotes: 3

carlosdc
carlosdc

Reputation: 12142

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

Upvotes: 3

Related Questions