How to Convert a Counter to a Plain Dict with Sorted Items in Python
This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.
Python code
15 linesfrom collections import Counter
def counter_to_sorted_dict(counter):
"""Convert a Counter to a plain dict with sorted items."""
return dict(sorted(counter.items()))
if __name__ == "__main__":
# Example usage
data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
print("Original Counter:")
print(data)
print("\nConverted to plain dict with sorted keys:")
result = counter_to_sorted_dict(data)
print(result)
print("\nType:", type(result).__name__)
Output
Original Counter:
Counter({'apple': 3, 'banana': 2, 'cherry': 1, 'date': 1})
Converted to plain dict with sorted keys:
{'apple': 3, 'banana': 2, 'cherry': 1, 'date': 1}
Type: dict
How it works
counter.items() returns key-value pairs in insertion order (Python 3.7+), so we wrap sorted() around it to get alphabetical key order. dict() then constructs a plain dictionary from the sorted tuple list. The result is a standard dict with the same data as the Counter but sorted by key, which is useful for deterministic output, logging, or comparisons. Note that this does not modify the original Counter; it returns a new dict.
Common mistakes
- Forgetting that `dict()` on a Counter directly doesn't sort the keys, so you need `sorted()` explicitly.
- Assuming `sorted(counter)` returns a dict; it returns a list of keys, so you must use `items()`.
- Modifying the original Counter in place; this function returns a new dict without side effects.
- Not handling non-string keys where sorting may fail if types are mixed.
Variations
- Use `dict(sorted(counter.items(), key=lambda x: x[0]))` to sort by key explicitly.
- Sort by value descending with `dict(sorted(counter.items(), key=lambda x: x[1], reverse=True))`.
Real-world use cases
- Preparing frequency counts for a report where alphabetical order is expected for readability.
- Creating a stable, hashable dictionary representation for caching or memoization in data processing pipelines.
- Transforming a Counter into a plain dict before serializing to JSON for API responses.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.