How to sort Counter by value? - python
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Sorting a Counter by value is a frequent step in frequency analysis, log summarization, and NLP tasks. Python offers built-in methods and sorting helpers that make this straightforward. The key is choosing output shape and sort direction that match your downstream logic.
Build and Inspect a Counter
A Counter maps items to counts and supports fast increment operations.
Counter behaves like a dictionary with extra frequency utilities.
Sort by Count with sorted
Use sorted(counter.items(), key=...) for full control.
This returns a list of (item, count) tuples.
Use most_common for Top Frequencies
For top-k tasks, most_common is concise and optimized for frequency workflows.
most_common is usually the best choice when you only need highest counts.
Stable Tie-Break Sorting
When counts tie, add secondary key rules for deterministic output.
Deterministic ordering matters in tests and reproducible reports.
Convert Sorted Results Back to Ordered Mapping
If you need dictionary-like access after sorting, create an ordered dict object.
In Python versions with insertion-ordered dict behavior, regular dict can also preserve sorted insertion order.
Performance Notes
For very large counters, avoid sorting all items if only top few are needed. most_common(k) is more efficient than full sort for small k.
If analysis runs repeatedly, cache sorted outputs when input is unchanged. This is useful in dashboards and periodic reports.
Grouping and Ranking Frequency Buckets
After sorting counts, you may need grouped summaries by rank bands for dashboards. Build these from sorted pairs in one pass.
This pattern helps convert raw counts into actionable tiers for alerts, prioritization, or content ranking workflows.
Choosing Output Shape
If downstream code needs random access by key, keep a mapping plus a sorted list for display. If only ranked output is needed, tuples from sorted results are simpler and cheaper.
Reusable Utility Function
Encapsulate sorting logic in one helper so behavior and tie-break rules remain consistent across scripts, notebooks, and production jobs.
Common Pitfalls
A common pitfall is sorting keys only, which ignores counts and produces incorrect frequency order.
Another issue is forgetting reverse=True when expecting descending frequency output.
Developers also rely on incidental tie ordering, leading to flaky tests across environments.
A final mistake is repeatedly sorting inside loops instead of sorting once and reusing the result.
Summary
Counterstores frequency data and supports convenient aggregation.- Use
sorted(counter.items(), key=...)for custom order control. - Use
most_commonfor top-k frequency queries. - Add tie-break rules for deterministic results.
- Choose full sort or top-k extraction based on performance needs.
Related reading
- How to sort depended objects by dependency
- How to sort faster than n log n given a strong condition on the list?
- How to sort in-place using the merge sort algorithm?
- How to sort List of objects by some property
- How to sort one list based on another?
- How to sort two arrays with one being sorted based on the sorting of the other?
- How to sort mongodb with pymongo
- How to sort pandas dataframe by one column

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.