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.
Python code
10 linesfrom 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
{'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
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.