How to find most common value for each key in list of dictionary?

Question:

I’ve got problem with given line of code.

 age_with_category =    [{18: 'book'}, {18: 'electronic'}, {43: 'electronic'}, {18: 'book'}, {18: 'book'}, {43:'electronic'}]
   

The case is to find for each age most common value.

That’s the way i wanted to find solution

age_of_users = [18, 18, 43, 18, 18, 43]
    print(Counter(category[age] for age in age_of_users for category in age_with_category).most_common(1))
    
proper answer is = [{18: 'book'}, {43: 'electronic'}]
Asked By: FrozenChicken

||

Answers:

I think you can map lust of dictionary into another dictionary and find the most common from the list of values,

from collections import Counter
final = {}

for d in age_with_category:
    for key, value in d.items():
        if key in final:
            final[key].append(value)
        else:
            final[key] = [value]

print(final)
# {18: ['book', 'electronic', 'book', 'book'], 43: ['electronic', 'electronic']}

result = {key: Counter(value).most_common(1)[0][0] for key, value in final.items()}
print(result)
# {18: 'book', 43: 'electronic'}
Answered By: Rahul K P

A defaultdict of Counters makes summing the most common categories by age pretty easy:

from collections import defaultdict, Counter

age_with_category =    [{18: 'book'}, {18: 'electronic'}, {43: 'electronic'}, {18: 'book'}, {18: 'book'}, {43:'electronic'}]

# Count category counts grouped by age
cat_counts_by_age = defaultdict(Counter)
for d in age_with_category:
    for k, v in d.items():
        cat_counts_by_age[k][v] += 1

# For each age and associated set of category counts, extract the most common category
answer = [{age: cat_counts.most_common(1)[0][0]} for age, cat_counts in cat_counts_by_age.items()]
print(answer)

Try it online!

Answered By: ShadowRanger
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.