Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count occurrences using a dictionary

Count how many times each (hashable) item appears in an iterable and return a dictionary of counts.

Python practice8 minList & Dictionary PatternsBeginnerLast updated March 20, 2026

Problem statement

Given an iterable of hashable items (e.g., strings, numbers, tuples, booleans), return a dictionary where each key is an item from the iterable and its value is the number of times it appears. The order of keys in the output should reflect the order in which distinct items first appear in the input. Implement: count_occurrences(iterable) -> dict Notes: - You may assume all items are hashable. - Do not use collections.Counter; implement using a plain dict so insertion order is predictable.

Task

Implement a function that tallies occurrences of hashable items and returns a dictionary mapping items to their counts.

Examples

string list

Input

count_occurrences(['a', 'b', 'a'])

Output

{'a': 2, 'b': 1}

'a' appears twice and 'b' once; 'a' appears first so it appears first in the dict.

Input format

A Python iterable containing hashable items.

Output format

A Python dict mapping each distinct item to its integer count.

Constraints

All items are hashable. Use a plain dict (no external modules).

Samples

Sample 1

Input

count_occurrences([1, 2, 1, 3, 1])

Output

{1: 3, 2: 1, 3: 1}

1 appears three times; 2 and 3 appear once each.