Python Practice › Dictionary Programs › Program 37
Count frequencies in a list
Write a Python program to count how often each item appears in a list, using a dictionary.
Input
[2, 5, 8, 1, 2, 6, 8, 5]
Output
{1: 1, 2: 2, 5: 2, 6: 1, 8: 2}Approach
get(x, 0) + 1, then sort by key.
Solution
items = [2, 5, 8, 1, 2, 6, 8, 5]freq = {}for x in items: freq[x] = freq.get(x, 0) + 1print(dict(sorted(freq.items())))Output
{1: 1, 2: 2, 5: 2, 6: 1, 8: 2}Learn the concept
New to this topic? Read the lesson, then come back.