How to Sort a Dictionary in Python

What you’ll build or solve

You’ll sort a dictionary by key or by value and get a predictable order you can use for output or further processing.

When this approach works best

Sorting a dictionary works well when you:

  • Print results in a stable order, like sorting a score table by points.
  • Build ranked outputs, like listing products by price or users by activity count.
  • Prepare data for display, like sorting settings or headers alphabetically.

Avoid sorting a dictionary when order does not matter, or when you need fast repeated lookups by “top value.” For that, use max(), heapq, or keep a separate ranked structure.

Prerequisites

  • Python installed
  • You know what a dictionary is

Step-by-step instructions

1) Sort by key

Use sorted() on a dictionary to sort its keys. This gives you a list of keys in sorted order.

scores= {"mila":12,"ana":30,"ivan":22}
sorted_keys=sorted(scores)

print(sorted_keys)

If you want a dictionary that keeps that key order, build one from the sorted keys.

scores= {"mila":12,"ana":30,"ivan":22}
sorted_by_key= {k:scores[k]forkinsorted(scores)}

print(sorted_by_key)

Option A: Reverse key order

scores= {"mila":12,"ana":30,"ivan":22}
sorted_by_key_desc= {k:scores[k]forkinsorted(scores,reverse=True)}

print(sorted_by_key_desc)

What to look for:

sorted(scores) sorts keys, not key-value pairs. Use .items() when you want to sort by values.


2) Sort by value

Sort dictionary items with sorted(d.items(), key=...). Each item is a (key, value) tuple.

scores= {"mila":12,"ana":30,"ivan":22}
pairs=sorted(scores.items(),key=lambdaitem:item[1])

print(pairs)

Build a dictionary from those sorted pairs if you want to keep the order.

scores= {"mila":12,"ana":30,"ivan":22}
sorted_by_value=dict(sorted(scores.items(),key=lambdaitem:item[1]))

print(sorted_by_value)

Option A: Highest values first

scores= {"mila":12,"ana":30,"ivan":22}
sorted_by_value_desc=dict(
sorted(scores.items(),key=lambdaitem:item[1],reverse=True)
)

print(sorted_by_value_desc)

Option B: Sort by value, then key (tie-breaker)

This helps when values repeat.

scores= {"mila":30,"ana":30,"ivan":22}
sorted_pairs=sorted(scores.items(),key=lambdaitem: (item[1],item[0]))
sorted_by_value_then_key=dict(sorted_pairs)

print(sorted_by_value_then_key)

What to look for:

Sorting returns a new list or dict. The original dictionary does not reorder in place.


3) Sort by custom rules

Use a key function for case-insensitive sorting, multi-field sorting, or type conversion.

names= {"Mila":1,"ana":2,"Ivan":3}
sorted_names= {k:names[k]forkinsorted(names,key=str.casefold)}

print(sorted_names)

Option A: Convert string values to numbers before sorting

prices= {"apple":"10","banana":"2","pear":"7"}
sorted_prices=dict(
sorted(prices.items(),key=lambdaitem:int(item[1]))
)

print(sorted_prices)

What to look for:

key= changes how sorting compares items. It does not change the original data. Convert inside key when you only need the converted form for ordering.


Examples you can copy

Example 1: Print a dictionary as a sorted table by key

settings= {
"timeout":30,
"retries":3,
"base_url":"https://example.com",
}

forkeyinsorted(settings):
print(key,"=",settings[key])

Example 2: Rank items by value for display

cart= {"apples":4,"bananas":2,"pears":5}

forname,qtyinsorted(
cart.items(),key=lambdaitem:item[1],reverse=True
):
print(name,qty)

Example 3: Sort by value and keep stable tie-breaking

votes= {"Option A":10,"Option B":10,"Option C":7}

sorted_votes=dict(
sorted(votes.items(),key=lambdaitem: (-item[1],item[0]))
)

print(sorted_votes)

Example 4: Create a “top 3” leaderboard

scores= {"Mila":120,"Ana":300,"Ivan":220,"Lea":180}

top_3=sorted(
scores.items(),key=lambdaitem:item[1],reverse=True
)[:3]

print(top_3)

Example 5: Sort nested data by a field

users= {
"u1": {"name":"Naomi","points":12},
"u2": {"name":"Ivan","points":30},
"u3": {"name":"Lea","points":22},
}

sorted_users=sorted(
users.items(),
key=lambdaitem:item[1]["points"],
reverse=True,
)

print(sorted_users)

Common mistakes and how to fix them

Mistake 1: Sorting the dictionary and expecting it to change in place

What you might do

scores= {"mila":12,"ana":30,"ivan":22}
sorted(scores)
print(scores)

Why it breaks

sorted() returns a new result. It does not reorder the original dictionary.

Fix

scores= {"mila":12,"ana":30,"ivan":22}
sorted_by_key= {k:scores[k]forkinsorted(scores)}
print(sorted_by_key)

Mistake 2: Sorting values as strings instead of numbers

What you might do

prices= {"apple":"10","banana":"2"}
sorted_prices=dict(
sorted(prices.items(),key=lambdaitem:item[1])
)
print(sorted_prices)

Why it breaks

String sorting is lexicographic, so "10" comes before "2".

Fix

prices= {"apple":"10","banana":"2"}
sorted_prices=dict(
sorted(prices.items(),key=lambdaitem:int(item[1]))
)
print(sorted_prices)

Troubleshooting

If you see TypeError: '<' not supported between instances, your keys or values include mixed types. Convert them inside the key function.

If the order looks wrong for text with mixed case, sort with key=str.casefold.

If you need the sorted output to stay ordered, build a new dict from the sorted pairs, or keep the sorted list of pairs.

If sorting is slow on large data, sort once and reuse the result, or use heapq.nlargest() when you only need the top results.


Quick recap

  • Sort by key with sorted(d) and rebuild if you need an ordered dict.
  • Sort by value with sorted(d.items(), key=lambda item: item[1]).
  • Use reverse=True for descending order.
  • Add tie-breakers with tuple keys like (value, key) or (-value, key).
  • For top N, sort pairs and slice the list.