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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

15 lines
Python 3.9+
from 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

stdout
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

  1. Use `dict(sorted(counter.items(), key=lambda x: x[0]))` to sort by key explicitly.
  2. 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

Run this sample

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

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.