Question

Sort a Dictionary by Key in Python

pythonsortingdictionary

Question

How can I sort a Python dictionary by its keys?

For example, given this dictionary:

numbers = {2: 3, 1: 89, 4: 5, 3: 0}

I want a dictionary whose items appear in ascending key order:

{1: 89, 2: 3, 3: 0, 4: 5}

Short Answer

You will learn how Python dictionaries store key-value pairs, how sorted() orders dictionary keys, and how to build a new dictionary with items inserted in sorted key order. You will also learn when sorting a dictionary is useful and when sorting only its keys is enough.

Concept

A Python dictionary maps keys to values. For example, in {2: 3}, 2 is the key and 3 is its associated value.

To sort a dictionary by key, first sort its keys, then create a new dictionary in that order:

numbers = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_numbers = dict(sorted(numbers.items()))

numbers.items() produces key-value pairs such as (2, 3) and (1, 89). By default, sorted() compares the first element of each pair, which is the key. Finally, dict(...) builds a dictionary from those sorted pairs.

In modern Python (3.7+), dictionaries preserve insertion order. Therefore, the newly created dictionary keeps the sorted order when you print it or iterate over it.

Sorting matters when you need predictable output: reports, exported files, logs, test results, or user-facing lists. It does not change the relationship between a key and its value; it only changes the order in which items are stored and displayed.

Mental Model

Think of a dictionary as a set of labelled drawers:

  • The key is the label on a drawer.
  • The value is what is inside it.

Your drawers may have been added in a random order: 2, 1, 4, 3. Sorting by key means arranging the drawers by their labels: 1, 2, 3, 4.

The contents stay with the same drawer. Sorting {2: 3, 1: 89} never changes it into {1: 3, 2: 89}. Instead, it becomes {1: 89, 2: 3} because each value remains attached to its original key.

Take Quiz

Syntax and Examples

The most common approach is:

sorted_dictionary = dict(sorted(original_dictionary.items()))

Example:

numbers = {2: 3, 1: 89, 4: 5, 3: 0}

sorted_numbers = dict(sorted(numbers.items()))

print(sorted_numbers)

Output:

{1: 89, 2: 3, 3: 0, 4: 5}

Sort in descending key order

Pass reverse=True to sorted():

numbers = {2: 3, 1: 89, 4: 5, 3: 0}

largest_key_first = dict(sorted(numbers.items(), reverse=True))

print(largest_key_first)

Output:

{4: 5, 3: 0, 2: 3, 1: 89}

Sort only the keys

If you only need to process keys in order, do not create a new dictionary:

numbers = {2: 3, 1: 89, 4: 5, 3: 0}

for key in sorted(numbers):
    print(key, numbers[key])

Output:

1 89
2 3
3 0
4 5

Calling sorted(numbers) works because iterating over a dictionary produces its keys.

Step by Step Execution

Consider this code:

numbers = {2: 3, 1: 89, 4: 5, 3: 0}
result = dict(sorted(numbers.items()))

Here is what happens:

  1. numbers.items() creates a view of the dictionary's pairs:

    dict_items([(2, 3), (1, 89), (4, 5), (3, 0)])
    
  2. sorted(...) sorts these pairs. Since no custom sorting rule was provided, Python compares the first part of each pair: the keys.

    [(1, 89), (2, 3), (3, 0), (4, 5)]
    
  3. dict(...) turns the sorted list of pairs back into a dictionary.

    {1: 89, 2: 3, 3: 0, 4: 5}
    
  4. Because Python dictionaries preserve insertion order in Python 3.7 and later, iterating over result visits keys in the order 1, 2, 3, 4.

Real World Use Cases

Sorting dictionary keys is useful whenever output should be stable and easy to read.

  • Configuration output: Display configuration options alphabetically so users can find settings quickly.
  • API responses: Produce predictable JSON-like data for documentation, debugging, or snapshots.
  • Reports: List sales totals by product code, date, or region in a meaningful order.
  • Data exports: Write dictionary data to a text or CSV file in a repeatable order.
  • Testing: Avoid flaky text comparisons by sorting data before creating expected output.
  • Logs and debugging: Print fields in a consistent order so two log entries are easier to compare.

Example: generating a simple report from scores:

scores = {102: 75, 101: 88, 103: 91}

for student_id in sorted(scores):
    print(f"Student {student_id}: {scores[student_id]}")
Student 101: 88
Student 102: 75
Student 103: 91
Take Quiz

Real Codebase Usage

In real projects, developers often avoid sorting until the moment it is needed. The original dictionary may be best kept in its natural insertion order, while a report or response is sorted at the boundary of the application.

Sort while rendering or exporting

settings = {"theme": "dark", "autosave": True, "font_size": 14}

for name, value in sorted(settings.items()):
    print(f"{name}: {value}")

This is useful when displaying data but no later code requires a new sorted dictionary.

Return a sorted mapping from a helper function

def sorted_by_key(data):
    return dict(sorted(data.items()))

status_codes = {500: "Server Error", 200: "OK", 404: "Not Found"}
print(sorted_by_key(status_codes))

Use a custom key for case-insensitive text

Normal string sorting places uppercase and lowercase letters according to Unicode ordering. For alphabetical sorting that ignores case, use key=str.lower:

users = {"zoe": 3, "Alice": 1, "bob": 2}
ordered_users = dict(sorted(users.items(), key=lambda item: item[0].lower()))

print(ordered_users)

A dictionary's keys must remain unique. Sorting rearranges items; it does not validate, merge, or modify keys.

Common Mistakes

Expecting sorted() to return a dictionary

sorted() always returns a list.

numbers = {2: 3, 1: 89}
result = sorted(numbers.items())

print(result)
# [(1, 89), (2, 3)]

If you need a dictionary, wrap the result in dict(...):

result = dict(sorted(numbers.items()))

Sorting values accidentally

This code sorts pairs by their values, not their keys:

numbers = {2: 3, 1: 89, 4: 5, 3: 0}
wrong_for_key_sorting = dict(sorted(numbers.items(), key=lambda item: item[1]))

Use sorted(numbers.items()) for the default ascending key sort.

Assuming the original dictionary is changed

Sorting creates a new list or a new dictionary. It does not rearrange the existing dictionary in place.

numbers = {2: 3, 1: 89}
dict(sorted(numbers.items()))

print(numbers)
# {2: 3, 1: 89}

Assign the result if you need it later:

numbers = dict(sorted(numbers.items()))

Using keys that cannot be compared

Keys must be mutually sortable. Mixing unrelated types can fail in Python 3:

mixed = {1: "number", "two": "text"}

# dict(sorted(mixed.items()))  # TypeError

Use consistent key types, or provide a conversion rule such as key=lambda item: str(item[0]) when that ordering makes sense.

Relying on sorted display in old Python versions

Python 3.7+ guarantees dictionary insertion order. If code must support older Python versions, use the sorted list of pairs for ordered iteration, or use collections.OrderedDict where appropriate.

Comparisons

ApproachResultBest use
sorted(data)A sorted list of keysYou only need keys in order.
sorted(data.items())A sorted list of (key, value) tuplesYou need ordered pairs but not a dictionary.
dict(sorted(data.items()))A new dictionary inserted in key orderYou want an ordered dictionary result in Python 3.7+.
sorted(data.items(), key=lambda item: item[1])Pairs sorted by valueYou want to order items using values.
sorted(data.items(), reverse=True)Pairs in descending key orderYou want largest or last keys first.

Sorting by key versus sorting by value

prices = {"banana": 2.5, "apple": 3.0, "pear": 2.0}

by_key = dict(sorted(prices.items()))
by_value = dict(sorted(prices.items(), key=lambda item: item[1]))

print(by_key)
# {'apple': 3.0, 'banana': 2.5, 'pear': 2.0}

print(by_value)
# {'pear': 2.0, 'banana': 2.5, 'apple': 3.0}

Key sorting answers “which label comes first?” Value sorting answers “which associated amount comes first?”

Take Quiz

Cheat Sheet

# Sort keys and create a new dictionary
ordered = dict(sorted(data.items()))

# Sort keys in descending order
ordered = dict(sorted(data.items(), reverse=True))

# Iterate through keys in ascending order
for key in sorted(data):
    print(key, data[key])

# Get sorted key-value pairs as a list
pairs = sorted(data.items())

# Sort items by value instead of key
by_value = dict(sorted(data.items(), key=lambda item: item[1]))

# Sort string keys without considering case
case_insensitive = dict(
    sorted(data.items(), key=lambda item: item[0].lower())
)

Key points:

  • sorted() returns a list.
  • dict.items() provides (key, value) pairs.
  • Sorting pairs without a key= argument sorts by key first.
  • Python 3.7+ dictionaries retain insertion order.
  • The original dictionary is unchanged unless you assign the new result.

FAQ

Does Python sort dictionaries automatically?

No. A dictionary preserves the order in which items were inserted in Python 3.7+, but it does not automatically arrange keys alphabetically or numerically.

How do I sort a dictionary by key in Python?

Use dict(sorted(data.items())) to create a new dictionary with items inserted in ascending key order.

Can I use sorted(my_dict) instead of sorted(my_dict.items())?

Yes, but it returns only a list of sorted keys. Use it when iterating: for key in sorted(my_dict):.

Does sorting a dictionary modify the original dictionary?

No. sorted() creates a new list. Create and assign a new dictionary if you need to keep the sorted result.

How do I sort dictionary keys in reverse order?

Use dict(sorted(data.items(), reverse=True)).

Why does sorting my dictionary raise a TypeError?

Some keys cannot be compared with each other, such as an integer and a string in Python 3. Use one consistent key type or provide a meaningful custom sorting function.

Can I sort a dictionary by value instead?

Yes. Use dict(sorted(data.items(), key=lambda item: item[1])) to sort by each pair's value.

Is a sorted dictionary a different data type?

No. dict(sorted(data.items())) returns a normal dict. Its iteration order reflects the order in which sorted items were inserted.

Take Quiz

Mini Project

Description

Build a small score report formatter. A program receives student IDs and scores in an arbitrary dictionary order, then prints a clear report ordered by student ID. This mirrors common tasks such as exporting records, producing reports, and generating stable output for tests.

Goal

Create a function that returns a score report with student records sorted by ID.

Requirements

Store at least four student ID-to-score pairs in a dictionary. Sort the records by student ID in ascending order. Print one formatted line for every student. Return the sorted dictionary from a function. Also demonstrate descending order in one additional output.

Take Quiz

Keep learning

Related questions

View more