Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 6

Count item occurrences with a dictionary

Easy

10 minute session

Summary

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

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}

Explanation

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 input 0

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

Sample output 0

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

Explanation 0

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

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

07:44 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.