Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use sorted() on the dictionary’s items, then pass the sorted pairs to dict():
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))
Each expression creates a new dictionary. The original dictionary is not reordered in place. In current Python versions, the rebuilt dictionary iterates in the order in which those sorted pairs were inserted.
Sort a dictionary by key
A dictionary item is a (key, value) pair. When you sort those pairs without a key function, Python compares the first tuple element, so the keys determine the order.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →data = {'b': 2, 'a': 3, 'c': 1}
ordered = dict(sorted(data.items()))
print(ordered)
# {'a': 3, 'b': 2, 'c': 1}
The explicit form is useful when you want the criterion to be obvious:
#1 Best Overall
ordered = dict(
sorted(data.items(), key=lambda item: item[0])
)
Iterate by key without creating another dictionary
If you only need to print or process entries in key order, sort the keys and look up each value:
for key in sorted(data):
print(key, data[key])
sorted(data) returns the keys in ascending order. This avoids rebuilding a second mapping when a one-time traversal is all you need.
Sort a dictionary by value
Supply a key function that returns the value portion of each item. The callable receives one (key, value) tuple at a time.
data = {'b': 2, 'a': 3, 'c': 1}
ordered = dict(sorted(data.items(), key=lambda item: item[1]))
print(ordered)
# {'c': 1, 'b': 2, 'a': 3}
For readability, the same operation can use a named function:
def value_of(item):
return item[1]
ordered = dict(sorted(data.items(), key=value_of))
Descending values
Set reverse=True to reverse the sort direction:
highest_first = dict(
sorted(data.items(), key=lambda item: item[1], reverse=True)
)
# {'a': 3, 'b': 2, 'c': 1}
reverse=True reverses the result of the selected comparison key; it does not mutate the source dictionary.
Control ties with stable sorting
Python’s sort is stable. If two entries have equal comparison values, their relative order from the input sequence is retained.
Rank #2
data = {'first': 10, 'second': 5, 'third': 10}
ordered = dict(sorted(data.items(), key=lambda item: item[1]))
# {'second': 5, 'first': 10, 'third': 10}
Here, first remains before third because both values are 10 and that was their original order.
Recommended Free Tools
Value first, then key
Use a tuple key when ties should be resolved alphabetically by key:
ordered = dict(
sorted(data.items(), key=lambda item: (item[1], item[0]))
)
The first tuple element sorts by value; the second sorts equal-valued entries by key.
Descending values but ascending keys
A single reverse=True reverses both tuple components, which is not what you want when values should descend but keys should ascend. Use two stable passes, sorting by the secondary field first:
items = sorted(data.items(), key=lambda item: item[0])
items = sorted(items, key=lambda item: item[1], reverse=True)
ordered = dict(items)
The first pass establishes ascending key order. The second pass groups by descending value while stability preserves the key order inside each equal-value group.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Normalize values before comparing
Every value returned by the sort key must be mutually comparable. Mixed types can raise a TypeError, and textual values may need case normalization.
Case-insensitive text sorting
labels = {'one': 'Banana', 'two': 'apple', 'three': 'Cherry'}
ordered = dict(
sorted(labels.items(), key=lambda item: str(item[1]).lower())
)
# {'two': 'apple', 'one': 'Banana', 'three': 'Cherry'}
Converting to text and lowercasing gives the comparison a consistent form. Choose a normalization rule that matches your data rather than silently converting values whose original types matter.
Nested records
For dictionaries whose values are records, select the nested field:
people = {
'a': {'score': 9},
'b': {'score': 4},
'c': {'score': 7},
}
by_score = dict(
sorted(people.items(), key=lambda item: item[1]['score'])
)
If a record might not contain the field, decide whether to validate it first, provide a default, or deliberately let the missing-field error identify bad input. A default can be supplied with dict.get() when that behavior is appropriate:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchby_score = dict(
sorted(people.items(), key=lambda item: item[1].get('score', 0))
)
Does sorting change the original dictionary?
No. sorted() produces a new list of pairs, and dict() constructs a new dictionary from that list.
data = {'b': 2, 'a': 3}
ordered = dict(sorted(data.items()))
print(data) # {'b': 2, 'a': 3}
print(ordered) # {'a': 3, 'b': 2}
You can intentionally replace the variable with the new object:
data = dict(sorted(data.items(), key=lambda item: item[1]))
That assignment changes what data refers to; it still does not reorder an existing dictionary object in place.
Insertion order, regular dict, and OrderedDict
Regular dictionaries guarantee insertion order in Python 3.7 and later. Therefore, inserting sorted pairs into a new dict makes iteration and display follow that sorted sequence:
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsordered = dict(sorted(data.items(), key=lambda item: item[1]))
for key, value in ordered.items():
print(key, value)
This is an insertion order, not a continuously self-sorting mapping. If you add another key later, normal dictionary insertion rules apply; the new key is appended rather than automatically placed in its sorted position.
collections.OrderedDict is generally unnecessary merely to retain the result of a sort on modern Python. It can still matter when you target older Python versions or need its specialized reordering operations.
from collections import OrderedDict
ordered = OrderedDict(sorted(data.items(), key=lambda item: item[1]))
Choose the right form
| Need | Expression | Result |
|---|---|---|
| New dictionary by ascending key | dict(sorted(d.items())) |
Pairs ordered by key |
| New dictionary by ascending value | dict(sorted(d.items(), key=lambda item: item[1])) |
Pairs ordered by value |
| New dictionary by descending value | dict(sorted(d.items(), key=lambda item: item[1], reverse=True)) |
Largest comparison values first |
| One-time key-ordered traversal | for key in sorted(d): |
No rebuilt dictionary |
| Value with key tie-breaker | key=lambda item: (item[1], item[0]) |
Ascending value, then ascending key |
Performance and memory considerations
Sorting requires Python to materialize the entries being compared. A call on d.items() therefore creates a sorted list before dict() builds the result. For a large mapping, account for the temporary list and the second dictionary if you keep both objects.
For a single pass, prefer:
for key, value in sorted(data.items(), key=lambda item: item[1]):
process(key, value)
If you repeatedly need the same order while the data changes, consider whether a dictionary is the right primary structure. A normal dictionary does not maintain a sorted view automatically, so each requested sorted traversal performs the sorting work again.
Free tools Windows power users keep installed
One-click scans. No signup required.
Troubleshooting common errors
“dict” object has no attribute “sort”
Dictionaries do not provide a sort() method. Sort keys or items with the built-in sorted() function:
Best Value
ordered = dict(sorted(data.items()))
TypeError while comparing values
Your key function is returning values that cannot be compared with one another, such as incompatible types. Validate the data or normalize the comparison value:
ordered = dict(
sorted(data.items(), key=lambda item: str(item[1]))
)
Use this conversion only when text ordering is actually the intended rule.
Equal values appear in an unexpected order
Stable sorting preserves the entries’ incoming order. If that is not your desired tie policy, add a secondary key such as (item[1], item[0]), or use the two-pass method for mixed directions.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →The source dictionary seems unchanged
That is expected: sorting returns a new result. Keep the returned dictionary or assign it back to the variable if you want subsequent code to use the ordered mapping.
A newly added key is not in sorted position
A regular dictionary preserves insertion order; it does not continuously sort itself. Rebuild the ordered dictionary, or sort again when you need a fresh ordered view.
Or skip the browser setup
If this article is part of a workflow that also needs website screenshots—for example, generating a report whose dictionary data is rendered on a page—ScreenshotNeo can capture the URL with one request instead of configuring a browser.
Its pre-capture steps accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. It also provides an MCP server for AI agents, including Claude, Cursor, and other MCP clients.
One-call examples
See the parameter reference in the ScreenshotNeo documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo supports PNG, JPEG, WebP, and PDF output, plus full-page capture, CSS-element capture, device presets, custom viewport and retina scale, dark mode, lazy-image loading, custom CSS or JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Every feature is included on every plan. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

