Sort Unique Values by Frequency in Python
Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.
Python code
10 linesfrom 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
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
- Use `sorted(counts, key=counts.get, reverse=True)` for a shorter but less explicit approach
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.