How to Build a Frequency Map from a List in Python

This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

10 lines
Python 3.9+
from collections import Counter

def build_frequency_map(values):
    """Return a dictionary mapping each unique value to its frequency."""
    return dict(Counter(values))

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
    freq_map = build_frequency_map(data)
    print(freq_map)

Output

stdout
{'apple': 3, 'banana': 2, 'cherry': 1}

How it works

The Counter class from collections is a specialized dictionary designed for counting hashable objects. Counter(values) scans the list once and tallies each element efficiently. Wrapping it with dict() returns a plain dictionary, making the result easy to use in other code. This approach is fast, readable, and works with any iterable of hashable items.

Common mistakes

  • Trying to measure the frequency of unhashable items like lists or dictionaries, which raises a TypeError.
  • Forgetting that Counter is a subclass of dict and can be used directly without conversion, but converting clarifies intent.

Variations

  1. Use a manual loop with a dictionary: `freq = {}; for item in values: freq[item] = freq.get(item, 0) + 1`.

Real-world use cases

  • Counting word frequencies in a text document for NLP preprocessing.
  • Analyzing log files to find the most common error codes or IP addresses.
  • Tracking product sales counts from transaction records for inventory reporting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.