Sort dictionary by keys Dry Run in PYTHON

Sort dictionary by keys is an interactive PYTHON dry run visualizer from the Dict programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Sort dictionary by keys Program Code

# Sort dictionary by keys
unsorted = {"banana": 3, "apple": 5, "date": 2, "cherry": 4, "elderberry": 1}
print("Unsorted:", unsorted)

# Method 1: Using sorted() with dict() (Python 3.7+)
sorted_by_keys = dict(sorted(unsorted.items()))
print("Sorted by keys:", sorted_by_keys)

# Method 2: Ascending order (explicit)
sorted_asc = dict(sorted(unsorted.items(), key=lambda x: x[0]))
print("Ascending:", sorted_asc)

# Method 3: Descending order by keys
sorted_desc = dict(sorted(unsorted.items(), key=lambda x: x[0], reverse=True))
print("Descending by keys:", sorted_desc)

# Method 4: List of tuples (without converting to dict)
sorted_items = sorted(unsorted.items())
print("As list of tuples:", sorted_items)

View the complete Dict programs page.

Program Console Sort dictionary by keys Topic: PYTHON Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.