Sort Unique Values by Frequency in Python

Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.

Easy Python 3.6+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

10 lines
Python 3.6+
from collections import Counter

def sort_unique_by_frequency(values):
    counts = Counter(values)
    return sorted(counts.keys(), key=lambda x: (-counts[x], x))

if __name__ == "__main__":
    data = [4, 2, 2, 8, 3, 3, 1, 3, 5, 5, 5, 5, 1]
    result = sort_unique_by_frequency(data)
    print(f"Sorted unique values by frequency: {result}")

Output

stdout
Sorted unique values by frequency: [5, 3, 2, 4, 8, 1]

How it works

The Counter from the collections module builds a dictionary mapping each unique value to its occurrence count. The sorted function gets the unique keys and sorts them with a key that returns a tuple (-count, value). Negating the count sorts in descending order, and the value as the second element breaks ties in ascending order. This is efficient (O(n log n)) and works with any hashable data type, including strings and tuples.

Common mistakes

  • Forgetting to sort unique keys — sorting `counts.items()` yields tuples, not values
  • Using `key=lambda x: counts[x]` gives ascending frequency instead of descending
  • Mutating the original list while iterating when using alternative approaches
  • Assuming ties are broken predictably without providing a secondary sort key

Variations

  1. Use `sorted(counts, key=counts.get, reverse=True)` for a shorter but less explicit approach
  2. Convert to a list of `(value, count)` pairs and sort, then extract values

Real-world use cases

  • Ranking product categories by purchase frequency for a recommendation dashboard.
  • Aggregating log levels from an application to prioritize the most common errors.
  • Sorting most-used hashtags in a social media feed before rendering a trending widget.

Sponsored

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.