mk8efz
mk8efz

Reputation: 1424

Consolidate keys in list of dictionaries

I have a list of dictionaries with an arbitrary number of repetitive keys. I want to consolidate the keys and return lists for the values (even if the key is distinct, as in 'c' and 'd' in the example below):

input = [{'a': 2},
         {'b': 3},
         {'c': 1},
         {'a': 3},
         {'a': 5},
         {'d': 7},
         {'b': 4}]

Desired output:

output = [{'a': [2,3,5]}, {'b': [3, 4]}, {'c': [1]}, {'d': [7]}]

My current method is a bit of a mess, and I'm looking for simply the code

Upvotes: 1

Views: 32

Answers (1)

thebjorn
thebjorn

Reputation: 27311

A defaultdict seems like a good choice:

from collections import defaultdict
output = defaultdict(list)
for d in input:
    for key in d.keys():
        output[key].append(d[key])
output = [{k: output[k]} for k in output]

(print the intermediate values to see what is happening).

ps: you should probably not name a variable input since it shadows the global function by the same name..

Upvotes: 2

Related Questions