Counting with a Dictionary

~10 mincode completion

Write count_labels(labels) that takes a list of labels and returns a dictionary mapping each label to how many times it appeared.

["cat", "dog", "cat"] returns {"cat": 2, "dog": 1}.

Examples

Repeated labels are counted, not overwritten

Input
count_labels(["cat", "dog", "cat"])
Output
{"cat": 2, "dog": 1}

Every label appearing once gives every count as 1

Input
count_labels(["a", "b", "c"])
Output
{"a": 1, "b": 1, "c": 1}

One label repeated is counted correctly

Input
count_labels(["spam", "spam", "spam", "spam"])
Output
{"spam": 4}

Hints

Hint 1

A dictionary keyed by the value counts occurrences in one pass.

Hint 2

A common slip here: overwrote instead of incremented.

Requirements

  • labels: a list of strings

  • Return a dict mapping label -> count.

Constraints

  • Standard library only, no imports required

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

8 employers weight this skill

3 quant funds, 2 frontier labs, 2 big tech firms, 1 AI product company. Top match scores 80.

Python
def count_labels(labels):
    """
    Count how many times each label appears.

    Args:
        labels: a list of strings

    Returns:
        A dict mapping label -> count.
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.