To sort a dictionary in Python, sort its items and build a new dict: dict(sorted(d.items())) sorts by key, and dict(sorted(d.items(), key=lambda kv: kv[1])) sorts by value. Add reverse=True for descending order. Dictionaries themselves have no sort() method, but since Python 3.7 they keep insertion order, so the new dict stays in the sorted order. This guide covers sorting a Python dictionary by key (alphabetically, case-insensitive), by value, by nested values, and the top N items.
All examples were run with Python 3.12.5 in the Windows Command Prompt. Reference: Sorting HOW TO and dict in the Python docs.
Sort a dictionary by key and by value
prices = {"mango": 2.5, "apple": 1.2, "kiwi": 0.8, "banana": 0.5}
by_key = dict(sorted(prices.items())) # sort by key
by_value = dict(sorted(prices.items(), key=lambda kv: kv[1])) # sort by value
print("by key: ", by_key)
print("by value:", by_value)
Output:
by key: {'apple': 1.2, 'banana': 0.5, 'kiwi': 0.8, 'mango': 2.5}
by value: {'banana': 0.5, 'kiwi': 0.8, 'apple': 1.2, 'mango': 2.5}
d.items() gives (key, value) pairs. Tuples compare by their first element, so sorted(d.items()) orders by key; a key function that returns kv[1] orders by value.
Sort a dictionary by key alphabetically
Plain sorting compares characters by code point, so all uppercase letters come before lowercase ones. Use str.casefold() for true alphabetical order:
cities = {"boston": 675, "Chicago": 2746, "austin": 979, "Denver": 715}
print(sorted(cities)) # just the sorted keys (a list)
print(dict(sorted(cities.items()))) # uppercase keys come first
print(dict(sorted(cities.items(), key=lambda kv: kv[0].casefold()))) # true alphabetical order
print(dict(sorted(cities.items(), reverse=True))) # Z to A
Output:
['Chicago', 'Denver', 'austin', 'boston']
{'Chicago': 2746, 'Denver': 715, 'austin': 979, 'boston': 675}
{'austin': 979, 'boston': 675, 'Chicago': 2746, 'Denver': 715}
{'boston': 675, 'austin': 979, 'Denver': 715, 'Chicago': 2746}
Sort a dictionary by value (ascending and descending)
from operator import itemgetter
stock = {"pens": 120, "notebooks": 45, "folders": 80, "staplers": 12}
print(dict(sorted(stock.items(), key=itemgetter(1)))) # lowest first
print(dict(sorted(stock.items(), key=itemgetter(1), reverse=True))) # highest first
print(sorted(stock, key=stock.get, reverse=True)[:2]) # keys of the top 2 values
from collections import Counter
print(Counter(stock).most_common(2)) # top 2 as (key, value) pairs
Output:
{'staplers': 12, 'notebooks': 45, 'folders': 80, 'pens': 120}
{'pens': 120, 'folders': 80, 'notebooks': 45, 'staplers': 12}
['pens', 'folders']
[('pens', 120), ('folders', 80)]
itemgetter(1), reverse=True, and two ways to get the top items.A sorted dict does not stay sorted
The result of dict(sorted(...)) is an ordinary dictionary. New keys are added at the end, so sort again when needed (or keep the data in a sorted list):
d = {"c": 3, "a": 1, "b": 2}
d_sorted = dict(sorted(d.items()))
print(d_sorted)
d_sorted["aa"] = 0 # new keys go to the END: a dict keeps insertion order,
print(d_sorted) # it does not stay sorted by itself
print(dict(sorted(d_sorted.items()))) # sort again when you need it
Output:
{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'b': 2, 'c': 3, 'aa': 0}
{'a': 1, 'aa': 0, 'b': 2, 'c': 3}
Sort by a nested value or by two keys
employees = {
"E03": {"name": "Cara", "dept": "IT", "salary": 72000},
"E01": {"name": "Anna", "dept": "HR", "salary": 65000},
"E02": {"name": "Ben", "dept": "IT", "salary": 81000},
}
by_salary = dict(sorted(employees.items(), key=lambda kv: kv[1]["salary"], reverse=True))
for emp_id, info in by_salary.items():
print(emp_id, info["name"], info["salary"])
# two keys: department, then salary (highest first)
for emp_id, info in sorted(employees.items(), key=lambda kv: (kv[1]["dept"], -kv[1]["salary"])):
print(info["dept"], info["name"], info["salary"])
Output:
E02 Ben 81000
E03 Cara 72000
E01 Anna 65000
HR Anna 65000
IT Ben 81000
IT Cara 72000
Sort a list of dictionaries by a key
A related task: when you have a list of dicts, sort the list with a key that reads the field:
people = [{"name": "Dev", "age": 31}, {"name": "Anna", "age": 25}, {"name": "Ben", "age": 31}]
print(sorted(people, key=lambda p: p["age"]))
print(sorted(people, key=lambda p: (-p["age"], p["name"]))) # oldest first, then by name
Output:
[{'name': 'Anna', 'age': 25}, {'name': 'Dev', 'age': 31}, {'name': 'Ben', 'age': 31}]
[{'name': 'Ben', 'age': 31}, {'name': 'Dev', 'age': 31}, {'name': 'Anna', 'age': 25}]
Common errors
mixed = {3: "three", "two": 2, 1: "one"}
try:
sorted(mixed)
except TypeError as e:
print("TypeError:", e)
print(sorted(mixed, key=str)) # compare the keys as strings
d = {"b": 2, "a": 1}
try:
d.sort() # dictionaries have no sort() method
except AttributeError as e:
print("AttributeError:", e)
Output:
TypeError: '<' not supported between instances of 'str' and 'int'
[1, 3, 'two']
AttributeError: 'dict' object has no attribute 'sort'
- TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’: the keys have mixed types; sort with
key=stror make the types consistent. - AttributeError: ‘dict’ object has no attribute ‘sort’: use
sorted(d.items())and build a new dict.
More Python dictionary tutorials:
- Sort a list of tuples by the second element
- Initialize a dictionary in Python
- Convert a dictionary to a string
- Get multiple keys from a dictionary
Frequently asked questions
How do I sort a dictionary by key in Python?
dict(sorted(d.items())) returns a new dictionary ordered by key. Use sorted(d) if you only need the sorted keys.
How do I sort a dictionary by value?
dict(sorted(d.items(), key=lambda kv: kv[1])), or key=operator.itemgetter(1). Add reverse=True for highest first.
How do I sort dictionary keys alphabetically ignoring case?
dict(sorted(d.items(), key=lambda kv: kv[0].casefold())).
Can I sort a dictionary in place?
No, dicts have no sort() method. Create a sorted copy with sorted() and dict(), or reassign it to the same name.
Does a dictionary stay sorted after I add keys?
No. Dictionaries keep insertion order (Python 3.7+), so new keys go to the end; sort again when needed.
How do I get the top N items by value?
sorted(d.items(), key=lambda kv: kv[1], reverse=True)[:n] or Counter(d).most_common(n).
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn