Python
Counter
Sorting
Data Structures
Programming Tips

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.

Practice algorithms

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.

python
1from collections import Counter
2
3words = ["api", "db", "api", "cache", "api", "db"]
4c = Counter(words)
5print(c)

Counter behaves like a dictionary with extra frequency utilities.

Sort by Count with sorted

Use sorted(counter.items(), key=...) for full control.

python
1from collections import Counter
2
3c = Counter("abracadabra")
4
5descending = sorted(c.items(), key=lambda item: item[1], reverse=True)
6ascending = sorted(c.items(), key=lambda item: item[1])
7
8print("desc:", descending)
9print("asc:", ascending)

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.

python
1from collections import Counter
2
3c = Counter(["error", "warn", "error", "info", "error", "warn"])
4
5print(c.most_common())      # all sorted descending
6print(c.most_common(2))     # top 2 only

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.

python
1from collections import Counter
2
3c = Counter(["b", "a", "c", "a", "b", "c"])
4
5# sort by count descending, then item ascending
6ordered = sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))
7print(ordered)

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.

python
1from collections import Counter, OrderedDict
2
3c = Counter(["x", "y", "x", "z", "y", "x"])
4ordered_pairs = sorted(c.items(), key=lambda kv: kv[1], reverse=True)
5ordered_counter = OrderedDict(ordered_pairs)
6print(ordered_counter)

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.

python
1from collections import Counter
2
3c = Counter(["a", "a", "b", "c", "c", "c", "d", "d"])
4ordered = sorted(c.items(), key=lambda kv: kv[1], reverse=True)
5
6high = [item for item, count in ordered if count >= 3]
7medium = [item for item, count in ordered if count == 2]
8low = [item for item, count in ordered if count == 1]
9
10print("high", high)
11print("medium", medium)
12print("low", low)

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

  • Counter stores frequency data and supports convenient aggregation.
  • Use sorted(counter.items(), key=...) for custom order control.
  • Use most_common for top-k frequency queries.
  • Add tie-break rules for deterministic results.
  • Choose full sort or top-k extraction based on performance needs.

Related reading
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.