Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count item occurrences with a dictionary

Count how many times each item appears in an iterable using a dictionary.

Python practice10 minDictionaries & SetsBeginnerLast updated March 18, 2026

Problem statement

Given an iterable (e.g., list or string), count the frequency of each element and return a dictionary where keys are the elements and values are their counts. The order of keys in the result should reflect the order each key first appears in the input.

Task

Create a function that returns a dictionary mapping each distinct item to the number of times it appears in the input sequence. Preserve the order of first appearance.

Examples

List with repeated items

Input

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

Output

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

The function returns counts: 'a' appears twice and 'b' once. 'a' appears before 'b', so it comes first in the dictionary.

Input format

A single iterable (commonly a list or string) passed to count_items(seq).

Output format

A dictionary mapping each distinct item to its occurrence count.

Constraints

Elements of the iterable must be hashable. The function should work for empty iterables and should preserve the order of first occurrence for keys.

Samples

Sample 1

Input

count_items(['x', 'x', 'y'])

Output

{'x': 2, 'y': 1}

x appears twice and y once; x appears before y in the result because it appeared first in the input.