Home > Net >  Merging Several Python Dictionaries Into a List, Elegantly
Merging Several Python Dictionaries Into a List, Elegantly

Time:09-25

I realize that there are a ton of these questions, but I can't find one for my particular use-case. I have...

a = {'type': 'Low', 'count': 184} 
b = {'type': 'Low', 'count': 186} 
c = {'type': 'Low', 'count': 97} 
d = {'type': 'Medium', 'count': 1000} 
e = {'type': 'High', 'count': 2000} 

I need to combine these dictionaries to:

{'Low': [184, 186, 97], 'Medium': [1000], 'High': [2000]}

This works aok:

a = {'type': 'Low', 'count': 184} 
b = {'type': 'Low', 'count': 186} 
c = {'type': 'Low', 'count': 97} 
d = {'type': 'Medium', 'count': 1000} 
e = {'type': 'High', 'count': 2000} 

new = [a,b,c,d,e]
result_dict = {}

for item in new:    
    for key, val in item.items():
        if key == 'type':
            print(key, val)
            print(result_dict.keys())
            if item['type'] not in result_dict.keys():
                result_dict[item['type']] = list()
            print(result_dict)
    print()

for item in new:    
    result_dict[item['type']].append(item['count'])
print(result_dict)

But I'm iterating over my initial list twice and it seems like there should be a much easier and more elegant way to do this. Help?

CodePudding user response:

You can use a dictionary whose values default to lists:

from collections import defaultdict

result_dict = defaultdict(list)
for d in new:
    result_dict[d['type']].append(d['count'])
    
print(result_dict)
defaultdict(<class 'list'>, 
    {'Low': [184, 186, 97], 'Medium': [1000], 'High': [2000]})

See the defaultdict documentation for details.

  • Related