How to Sort a Python Dictionary by Key or Value
Learn how to sort Python dictionaries by key, value, direction, and tie-breaker, with runnable examples, edge cases, and performance guidance.

Python dictionaries do not have a dict.sort() method. To sort one, pass its keys or key-value pairs to sorted(), then optionally build a new dictionary from the sorted pairs.
data = {'b': 2, 'a': 3, 'c': 1}
by_key = dict(sorted(data.items()))
by_value = dict(sorted(data.items(), key=lambda item: item[1]))
by_value_desc = dict(sorted(data.items(), key=lambda item: item[1], reverse=True))
print(by_key) # {'a': 3, 'b': 2, 'c': 1}
print(by_value) # {'c': 1, 'b': 2, 'a': 3}
print(by_value_desc) # {'a': 3, 'b': 2, 'c': 1}
sorted() returns a new list and leaves the source unchanged. Calling dict() on those pairs creates a new dictionary whose insertion order follows the sorted sequence. The Python tutorial documents both behaviors.
1. Sort a dictionary by key
When you sort data.items() without a key function, Python compares each pair from left to right. The first element is the dictionary key, so this sorts by key in ascending order.

data = {'banana': 3, 'apple': 5, 'cherry': 2}
sorted_data = dict(sorted(data.items()))
print(sorted_data)
# {'apple': 5, 'banana': 3, 'cherry': 2}
An explicit key function makes the rule visible:
sorted_data = dict(
sorted(data.items(), key=lambda item: item[0])
)
Use item[0] for the key and item[1] for the value. For a one-time iteration, you do not need to rebuild a dictionary:
for key in sorted(data):
print(key, data[key])
This is often the clearest choice when you only need predictable output, logging, or a report. sorted(data) produces the keys in sorted order.
Descending key order
reverse_keys = dict(sorted(data.items(), reverse=True))
print(reverse_keys)
# {'cherry': 2, 'banana': 3, 'apple': 5}
Because the pairs compare by key first, reverse=True reverses the key order. For keys that need case-insensitive ordering, normalize the key in the key function:
data = {'Zoo': 1, 'apple': 2, 'Banana': 3}
case_insensitive = dict(
sorted(data.items(), key=lambda item: item[0].lower())
)
print(case_insensitive)
# {'apple': 2, 'Banana': 3, 'Zoo': 1}
2. Sort a dictionary by value
Pass a key function that returns the value portion of each pair:
scores = {'Ada': 91, 'Linus': 88, 'Grace': 97}
by_score = dict(
sorted(scores.items(), key=lambda item: item[1])
)
print(by_score)
# {'Linus': 88, 'Ada': 91, 'Grace': 97}
The Sorting HOW TO explains that Python calls the key callable for each item and compares the returned values.
Descending values
highest_first = dict(
sorted(scores.items(), key=lambda item: item[1], reverse=True)
)
print(highest_first)
# {'Grace': 97, 'Ada': 91, 'Linus': 88}
reverse=True is the documented switch for descending order. It does not mutate the original mapping.
Sort values while preserving only the top entries
If you need only a ranking, keep the sorted pairs as a list and slice it. This avoids constructing a dictionary you will not use:
top_two = sorted(
scores.items(),
key=lambda item: item[1],
reverse=True
)[:2]
print(top_two)
# [('Grace', 97), ('Ada', 91)]
For very large inputs where you need only a small number of results, heapq.nlargest() can avoid a full sort:
from heapq import nlargest
top_two = nlargest(2, scores.items(), key=lambda item: item[1])
3. Tie-breaking equal values
Python’s sort is stable. If two entries produce equal comparison values, their original relative order is retained. That is useful when the input order already represents a priority.

data = {'first': 10, 'second': 5, 'third': 10}
result = dict(sorted(data.items(), key=lambda item: item[1]))
print(result)
# {'second': 5, 'first': 10, 'third': 10}
first remains before third because both values are 10 and the input placed first first.
Value ascending, key ascending
Use a tuple key when ties should be alphabetical:
data = {'zebra': 2, 'apple': 1, 'banana': 1}
result = dict(
sorted(data.items(), key=lambda item: (item[1], item[0]))
)
print(result)
# {'apple': 1, 'banana': 1, 'zebra': 2}
Value descending, key ascending
A tuple with a negated numeric value works when values are numbers:
result = dict(
sorted(data.items(), key=lambda item: (-item[1], item[0]))
)
For general comparable values, use two stable passes. Sort by the secondary key first, then by the primary key in the desired direction:
ordered = sorted(data.items(), key=lambda item: item[0])
ordered = sorted(ordered, key=lambda item: item[1], reverse=True)
result = dict(ordered)
The second sort preserves the alphabetical order wherever values tie. This stable multi-pass technique is described in the Sorting HOW TO.
4. Normalize values before comparing
All values returned by the key function must be mutually comparable. Mixed types such as integers and strings can raise TypeError in Python 3.
mixed = {'a': 10, 'b': '2'}
# sorted(mixed.items(), key=lambda item: item[1])
# TypeError: '<' not supported between instances of 'str' and 'int'
Choose a normalization rule that matches your data:
by_text = dict(
sorted(mixed.items(), key=lambda item: str(item[1]))
)
numbers = {'a': '10', 'b': '2', 'c': '30'}
by_number = dict(
sorted(numbers.items(), key=lambda item: int(item[1]))
)
For case-insensitive text values:
labels = {'a': 'Zebra', 'b': 'apple', 'c': 'Banana'}
result = dict(
sorted(labels.items(), key=lambda item: item[1].casefold())
)
casefold() is generally more suitable than lower() for case-insensitive Unicode comparisons.
5. Sort nested dictionaries and records
Select the nested field in the key function. This example sorts people by score:
people = {
'ada': {'score': 9, 'name': 'Ada'},
'grace': {'score': 7, 'name': 'Grace'},
'linus': {'score': 9, 'name': 'Linus'},
}
by_score = dict(
sorted(people.items(), key=lambda item: item[1]['score'])
)
print(by_score)
If a field may be missing, use a default and decide where missing records belong:
by_optional_score = dict(
sorted(
people.items(),
key=lambda item: item[1].get('score', float('-inf'))
)
)
For readability and reuse, replace a complex lambda with a named function:
def score_then_name(pair):
key, record = pair
return (record['score'], record['name'])
ordered = dict(sorted(people.items(), key=score_then_name))
6. Does sorting change the original dictionary?
No. sorted() creates a new list, and dict() creates a new dictionary:
data = {'b': 2, 'a': 1}
ordered = dict(sorted(data.items()))
print(data) # {'b': 2, 'a': 1}
print(ordered) # {'a': 1, 'b': 2}
print(data is ordered) # False
You can deliberately replace the variable:
data = dict(sorted(data.items(), key=lambda item: item[1]))
This does not reorder the existing object in place. Any other reference to the old dictionary still sees its original insertion order.
7. Insertion order in modern Python
Regular dictionaries preserve insertion order in Python 3.7 and later. Therefore, inserting sorted pairs into a new dict makes iteration, printing, JSON serialization, and many displays follow that order.
ordered = dict(sorted({'b': 2, 'a': 1}.items()))
for key, value in ordered.items():
print(key, value)
# a 1
# b 2
This is an ordering of iteration, not a permanently self-sorting mapping. Adding a key later follows normal insertion behavior:
ordered['aa'] = 99
print(list(ordered))
# ['a', 'b', 'aa']
If your program must support older Python versions or needs specialized reordering operations, collections.OrderedDict remains available. PEP 372 documents its historical purpose. For ordinary sorting on supported modern Python versions, a regular dictionary is usually sufficient.
8. Alternative patterns for common tasks
| Goal | Pattern |
|---|---|
| Sort keys for iteration | for key in sorted(data): ... |
| New dict by key | dict(sorted(data.items())) |
| New dict by value | dict(sorted(data.items(), key=lambda x: x[1])) |
| Descending order | Add reverse=True |
| Compound criterion | Return a tuple such as (x[1], x[0]) |
| Top N only | heapq.nlargest(n, data.items(), key=...) |
| Preserve duplicate records | Keep a list of pairs; dictionary keys cannot duplicate |
9. Performance, memory, and reliability
Sorting n dictionary entries takes O(n log n) time and creates a list of O(n) pairs. Rebuilding the dictionary requires additional memory for the result. If you only need one pass, iterate over sorted(data) or sorted(data.items(), ...) and avoid the second container.
For repeated reads, sort once and cache the resulting list or dictionary. If the source changes frequently, do not assume the old ordering remains valid; rebuild it after updates. For top-N dashboards, prefer nlargest() or nsmallest() when N is much smaller than the total number of entries.
Sorting is deterministic when comparison values and tie rules are deterministic. Normalize locale-sensitive strings explicitly, convert numeric text before comparing, and provide a tie-breaker when reproducible output matters.
10. Troubleshooting common errors
AttributeError: 'dict' object has no attribute 'sort'
Dictionaries do not expose a list-style sort() method. Use sorted(data.items()) and optionally wrap it with dict().
TypeError comparing unlike values
Your key function returns incompatible types, such as int and str. Convert them to one common type before sorting.
The output appears unsorted
Check that you used the returned value. sorted() does not modify its input. Assign the result to a variable or iterate over it directly.
Ties appear in an unexpected order
Equal keys retain their original order because sorting is stable. Add a second field to the key tuple or use the documented two-pass stable sort.
A new key is not in sorted position
A regular dictionary preserves insertion order; it does not continuously sort itself. Rebuild the dictionary after adding data, or maintain a separate sorted list for live rankings.
Nested records raise KeyError
The selected field is absent. Use record.get('field', default) and choose a default that sorts missing records where you want them.
11. Complete runnable example
from heapq import nlargest
products = {
'keyboard': {'price': 80, 'name': 'Keyboard'},
'mouse': {'price': 25, 'name': 'Mouse'},
'monitor': {'price': 240, 'name': 'Monitor'},
'webcam': {'price': 80, 'name': 'Webcam'},
}
by_name = dict(sorted(products.items(), key=lambda pair: pair[0]))
by_price = dict(sorted(products.items(), key=lambda pair: pair[1]['price']))
by_price_desc = dict(
sorted(
products.items(),
key=lambda pair: (-pair[1]['price'], pair[1]['name'])
)
)
top_two = nlargest(
2, products.items(), key=lambda pair: pair[1]['price']
)
print('By key:', by_name)
print('By price:', by_price)
print('Most expensive first:', by_price_desc)
print('Top two:', top_two)
12. Or skip the browser setup
If your workflow also needs screenshots of sorted reports, documentation pages, or generated HTML, ScreenshotNeo returns an image or PDF with one GET request. It handles the browser work for you.
cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo API documentation for all options. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status. An MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Can I sort a dictionary in place?
No. Build a new dictionary or sort an iterable view. Reassigning the variable replaces its reference but does not mutate the old object.
What is the shortest value-sort expression?
dict(sorted(data.items(), key=lambda item: item[1])).
How do I sort by key and then value?
Return both fields, for example key=lambda item: (item[0], item[1]). Reverse individual fields with a suitable transformation or stable multiple passes.
Why use a list instead of a dictionary?
A list of pairs keeps every entry and supports duplicate keys from an upstream source. A dictionary requires unique keys and is best when keyed lookup remains part of the result.
Does JSON preserve the sorted order?
Python emits dictionary entries in insertion order, and common JSON serializers iterate that order. Treat ordering as a presentation choice and verify the behavior of any downstream system that consumes the JSON.


