Count frequencies in a list

EasyDictionary Programs · 37 of 94

Write a Python program to count how often each item appears in a list, using a dictionary.

Advertisement
Input
[2, 5, 8, 1, 2, 6, 8, 5]
Output
{1: 1, 2: 2, 5: 2, 6: 1, 8: 2}

Approach

  1. get(x, 0) + 1, then sort by key.

Solution

Python
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.

More dictionary programs

← All 94 Dictionary Programs