Sort Dictionary by Key in Python

Learn how to sort a dictionary by key in Python using sorted(), dict(), lambda, itemgetter(), reverse=True, case-insensitive sorting, and nested dictionary examples.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Sort Dictionary by Key in Python

Modern Python dictionaries preserve insertion order. When you build a new dictionary from sorted key-value pairs, that dictionary displays and iterates in sorted key order. This guide shows the patterns you need for everyday sorting, reverse order, custom rules, JSON output, and older Python versions.

If you need to sort by value instead, see the companion article on value-based sorting. For dict fundamentals, see Python dictionary.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Quick answer: sort a dictionary by key

Use dict(sorted(my_dict.items())) to sort a dictionary by key. The sorted() call orders (key, value) pairs by key; dict() turns the result back into a dictionary that keeps that order in Python 3.7+.

python
my_dict = {"b": 2, "a": 1, "c": 3}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)
Output

After you run this, the printed dictionary shows keys in alphabetical order: a, then b, then c.


Quick reference

Task Use
Sort dictionary by key dict(sorted(my_dict.items()))
Sort keys only sorted(my_dict)
Sort by key in reverse order dict(sorted(my_dict.items(), reverse=True))
Print key-value pairs sorted by key for key in sorted(my_dict): print(key, my_dict[key])
Sort case-insensitively dict(sorted(my_dict.items(), key=lambda item: item[0].lower()))
Sort numeric keys dict(sorted(my_dict.items()))
Sort mixed-type keys Use a custom key or convert keys to strings carefully
Pretty-print sorted keys pprint.pprint(my_dict, sort_dicts=True)
JSON output sorted by key json.dumps(my_dict, sort_keys=True)
Old Python versions collections.OrderedDict(sorted(my_dict.items()))

Sort a dictionary by key using sorted()

sorted(my_dict.items()) sorts key-value pairs by key by default. Wrap the result with dict() when you need a new dictionary object.

In Python 3.7 and later, normal dict preserves insertion order as a language guarantee. That makes dict(sorted(...)) the main approach for most code today.

python
my_dict = {"b": 2, "a": 1, "c": 3}
sorted_dict = dict(sorted(my_dict.items()))

print(sorted_dict)
for key in sorted_dict:
    print(key, sorted_dict[key])
Output

The rebuilt dictionary iterates in key order: a, b, c. You do not need a manual loop or zip() for basic key sorting.


Sort dictionary keys only

sorted(my_dict) returns a sorted list of keys. sorted(my_dict.keys()) does the same thing and is optional.

Use this when you only need sorted keys and not a rebuilt dictionary:

python
my_dict = {"b": 2, "a": 1, "c": 3}

for key in sorted(my_dict):
    print(key, my_dict[key])
Output

Iterating over sorted(my_dict) is often better than creating a new dictionary when you only need sorted output for display or a one-time pass.


When you only want sorted display, loop over sorted keys and read values from the original dictionary:

python
my_dict = {"z": 26, "m": 13, "a": 1}

for key in sorted(my_dict):
    print(f"{key}: {my_dict[key]}")
Output

This pattern avoids building a second dictionary when printing or exporting lines is enough.


Sort dictionary by key in reverse order

Pass reverse=True to sorted() for descending key order:

python
my_dict = {"b": 2, "a": 1, "c": 3}
reverse_dict = dict(sorted(my_dict.items(), reverse=True))

print(reverse_dict)
Output

Keys appear from largest to smallest: c, b, a.


Sort dictionary by key using lambda

For normal key sorting, sorted(my_dict.items()) is enough. Use key= with a lambda function when you need custom key behavior:

python
my_dict = {"b": 2, "a": 1, "c": 3}

# Explicit but equivalent to the default key sort
by_key = dict(sorted(my_dict.items(), key=lambda item: item[0]))
print(by_key)

# Sort by lowercase key (case-insensitive)
words = {"Banana": 1, "apple": 2, "Cherry": 3}
case_insensitive = dict(sorted(words.items(), key=lambda item: item[0].lower()))
print(case_insensitive)

# Sort by key length
by_length = dict(sorted(words.items(), key=lambda item: len(item[0])))
print(by_length)
Output

Do not treat lambda as the primary method for basic alphabetical key sorting. Reach for it when the default comparison is not what you want.


Sort dictionary by key using itemgetter()

operator.itemgetter(0) selects the key from each (key, value) pair. It is an alternative to lambda item: item[0]:

python
from operator import itemgetter

my_dict = {"b": 2, "a": 1, "c": 3}
sorted_dict = dict(sorted(my_dict.items(), key=itemgetter(0)))
print(sorted_dict)
Output

Use itemgetter(0) for readability in pipelines that already import from operator.


Case-insensitive sort by key

String sorting is case-sensitive by default, so "Banana" can sort before "apple". Compare lowercase keys when you want case-insensitive order:

python
words = {"Banana": 1, "apple": 2, "Cherry": 3}

case_insensitive = dict(sorted(words.items(), key=lambda item: item[0].lower()))
print(case_insensitive)
Output

For more robust Unicode comparisons, use casefold() instead of lower():

python
words = {"Straße": 1, "STRASSE": 2}
folded = dict(sorted(words.items(), key=lambda item: item[0].casefold()))
print(folded)
Output

Sort dictionary by numeric keys

When keys are numbers, sorted() compares them numerically:

python
scores = {3: "c", 1: "a", 2: "b"}
print(dict(sorted(scores.items())))
Output

If numeric-looking keys are stored as strings, they sort alphabetically unless you convert them:

python
string_keys = {"10": 10, "2": 2, "1": 1}
print(dict(sorted(string_keys.items())))  # '1', '10', '2'

numeric_order = dict(sorted(string_keys.items(), key=lambda item: int(item[0])))
print(numeric_order)  # 1, 2, 10
Output

The string sort puts "10" before "2" because comparison is character by character.


Sort dictionary by key length or custom rule

Sort by key length when alphabetical order is not enough:

python
words = {"pear": 1, "fig": 2, "apple": 3}

by_length = dict(sorted(words.items(), key=lambda item: len(item[0])))
print(by_length)
Output

You can combine rules in one key function—for example, sort by length first and then alphabetically:

python
words = {"pear": 1, "fig": 2, "apple": 3, "kiwi": 4}

def sort_rule(item):
    key = item[0]
    return (len(key), key)

print(dict(sorted(words.items(), key=sort_rule)))
Output

Sort nested dictionary by outer keys

Sort the outer dictionary with dict(sorted(data.items())). Inner dictionaries are not sorted automatically:

python
data = {
    "b": {"x": 1, "a": 2},
    "a": {"y": 3, "z": 4},
}

outer_sorted = dict(sorted(data.items()))
print(outer_sorted)

# Sort inner dicts explicitly when needed
fully_sorted = {
    key: dict(sorted(inner.items()))
    for key, inner in sorted(data.items())
}
print(fully_sorted)
Output

Apply sorting at each level you care about. One sorted() call on the outer dict does not recurse into nested values.


Sort dictionary by key for JSON output

json.dumps() can sort keys in the serialized string. That returns JSON text, not a Python dictionary:

python
import json

my_dict = {"b": 2, "a": 1, "c": 3}
json_text = json.dumps(my_dict, sort_keys=True)
print(json_text)
print(type(json_text))
Output

Use sort_keys=True for stable logs, tests, and API payloads. When you need a sorted Python dict object, still use dict(sorted(my_dict.items())).


Pretty-print dictionary sorted by key

The pprint module formats dictionaries for display. With sort_dicts=True (the default in recent Python versions), keys appear sorted in the output:

python
import pprint

my_dict = {"b": 2, "a": 1, "c": 3}
pprint.pprint(my_dict, sort_dicts=True)
Output

This helps debugging and reading large mappings. It does not replace building a sorted dictionary when your program logic depends on key order in a dict object.


OrderedDict for old Python versions

In Python 3.7+, normal dict preserves insertion order as part of the language specification. In Python 3.6, CPython preserved order as an implementation detail. For code that must run on older interpreters, use collections.OrderedDict:

python
from collections import OrderedDict

my_dict = {"b": 2, "a": 1, "c": 3}
ordered = OrderedDict(sorted(my_dict.items()))

print(ordered)
print(list(ordered.keys()))
Output

On modern Python, prefer dict(sorted(my_dict.items())) unless you have a specific compatibility requirement.


Common mistakes to avoid

  • Thinking sorted(my_dict) returns a dictionary. It returns a list of keys.
  • Sorting keys but losing values. Always sort my_dict.items() when you need both parts.
  • Rebuilding a dictionary when you only need sorted output. A for key in sorted(my_dict) loop is often enough.
  • Using json.dumps(sort_keys=True) when you need a Python dict. JSON output is a string, not a mapping object.
  • Using pandas for a normal dictionary sort. The standard library is enough; pandas adds weight you rarely need here.
  • Sorting by value by mistake with key=my_dict.get. That orders keys by their values, not alphabetically by key name.
  • Forgetting reverse=True for descending order.
  • Expecting sorted order on Python versions before 3.7 without OrderedDict.
  • Sorting mixed key types such as strings and integers without a custom key function—Python 3 raises TypeError when comparisons are ambiguous.
  • Using zip(mydict.keys(), mydict.values()) unnecessarily. sorted(my_dict.items()) is simpler for key sorting.

Summary

To sort a dictionary by key in Python, use dict(sorted(my_dict.items())). That is the standard approach on Python 3.7 and later because the new dictionary keeps sorted insertion order. Use sorted(my_dict) when you only need a list of keys, and add reverse=True for descending order. Reach for lambda or itemgetter() when you need case-insensitive sorting, numeric string keys, or other custom rules. Use json.dumps(..., sort_keys=True) only when you want sorted JSON text, and use OrderedDict only for older Python compatibility. For value-based ordering, see the companion article on sorting by value.


References


Frequently Asked Questions

1. How do you sort a dictionary by key in Python?

Use dict(sorted(my_dict.items())). sorted() orders the key-value pairs by key, and dict() rebuilds a dictionary that keeps that order in Python 3.7+.

2. Does sorted(my_dict) return a sorted dictionary?

No. sorted(my_dict) returns a sorted list of keys. Wrap sorted pairs with dict() when you need a new dictionary object.

3. How do you sort a dictionary by key in reverse order?

Use dict(sorted(my_dict.items(), reverse=True)). Add reverse=True to sorted() for descending key order.

4. Do Python dictionaries preserve order after sorting?

Yes in Python 3.7 and later. A dict built from sorted items keeps insertion order, so iteration follows the sorted key order.

5. How do you sort dictionary keys case-insensitively?

Use dict(sorted(my_dict.items(), key=lambda item: item[0].lower())). For stronger Unicode handling, use casefold() instead of lower().

6. When should you use OrderedDict instead of dict?

Use collections.OrderedDict only when you must support Python versions before 3.7 where normal dict order was not guaranteed by the language.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …