Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Parse JSON into Python objectsE02. Count items with CounterE03. Compute a square root with mathE

Problem No 2

Count items with Counter

Easy

8 minute session

Summary

Use collections.Counter to count occurrences in an iterable and return counts deterministically.

Problem statement

Given an iterable (like a list, tuple, or string), count how many times each element appears. Return a regular dict mapping items to their counts. To keep results deterministic (so tests are stable), return the counts with keys sorted in ascending order (natural order for the key type).

Task

Implement a function that counts occurrences of items in any iterable and returns a dictionary of counts with deterministic key order.

Examples

Count integers

Input

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

Output

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

Explanation

Each value maps to the number of times it appears.

Input format

A single iterable: list/tuple/string/etc.

Output format

Return a dict where keys are items from the iterable and values are their counts. Keys should be sorted so the dict is deterministic.

Constraints

Use collections.Counter internally but ensure the returned dict has a deterministic ordering (sorted by key). Input elements will be hashable.

Samples

Sample input 0

count_items('banana')

Sample output 0

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

Explanation 0

Counts characters in the string. Keys are sorted alphabetically.

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.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.