Reputation: 3
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'}]
Upvotes: 0
Views: 218
Reputation: 16081
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'}
Upvotes: 0
Reputation: 155353
A defaultdict
of Counter
s 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)
Upvotes: 1