Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in sorted() function on the dictionary’s items, then pass the resulting pairs to dict(). The original dictionary is unchanged; the new dictionary receives entries in sorted insertion order.

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))

Use sorted(data) when you only need keys in order, and use a compound key or a stable two-pass sort when ties need a defined policy.

Sort a dictionary by key

Dictionary items are (key, value) tuples. Without a key argument, sorted() compares each tuple from left to right, so the first element—the dictionary key—determines the order.

data = {'b': 2, 'a': 3, 'c': 1}
sorted_by_key = dict(sorted(data.items()))
print(sorted_by_key)
# {'a': 3, 'b': 2, 'c': 1}

An explicit key function makes the criterion visible and is useful when the expression becomes more complex:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sorted_by_key = dict(
    sorted(data.items(), key=lambda item: item[0])
)

Iterate over sorted keys without rebuilding

If you only need to print, process, or look up values in key order, avoid creating another dictionary:

for key in sorted(data):
    print(key, data[key])

sorted(data) returns a list of keys. This is often the simplest and least memory-intensive choice for one-time iteration.

Sort a dictionary by value

Pass a key function that returns the value portion of each item. In lambda item: item[1], item[0] is the key and item[1] is the value.

data = {'b': 2, 'a': 3, 'c': 1}
sorted_by_value = dict(
    sorted(data.items(), key=lambda item: item[1])
)
print(sorted_by_value)
# {'c': 1, 'b': 2, 'a': 3}

For dictionaries whose values are records, select the field that should control the order:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
people = {
    'ada': {'score': 9},
    'grace': {'score': 4},
    'linus': {'score': 7},
}

by_score = dict(
    sorted(people.items(), key=lambda item: item[1]['score'])
)
print(by_score)
# {'grace': {'score': 4}, 'linus': {'score': 7}, 'ada': {'score': 9}}

Descending order

Set reverse=True on sorted() to reverse the result. The option works for key and value sorts alike.

highest_first = dict(
    sorted(data.items(), key=lambda item: item[1], reverse=True)
)
# {'a': 3, 'b': 2, 'c': 1}

keys_z_to_a = dict(
    sorted(data.items(), reverse=True)
)
# {'c': 1, 'b': 2, 'a': 3}

Ties, secondary keys, and stable sorting

Python’s sort is stable. If two entries produce the same comparison value, their existing relative order is retained. This gives you a predictable default tie policy:

data = {'first': 10, 'second': 5, 'third': 10}
ordered = dict(sorted(data.items(), key=lambda item: item[1]))
# {'second': 5, 'first': 10, 'third': 10}

Value ascending, then key ascending

Return a tuple from the key function. Python compares the value first and the key second:

ordered = dict(
    sorted(data.items(), key=lambda item: (item[1], item[0]))
)

Value descending, key ascending

A single reverse=True reverses both tuple components, which would put keys in descending order too. Sort twice instead: first by the secondary key, then by the primary key in descending order. Stability preserves the first ordering inside equal-value groups.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ordered_items = sorted(data.items(), key=lambda item: item[0])
ordered_items = sorted(
    ordered_items,
    key=lambda item: item[1],
    reverse=True,
)
ordered = dict(ordered_items)

Value descending, key descending

If both directions should be descending, a tuple and reverse=True are sufficient:

ordered = dict(
    sorted(data.items(), key=lambda item: (item[1], item[0]), reverse=True)
)

Normalize values before comparing

All values returned by the key function must be mutually comparable. Sorting a mixture of unrelated types, such as integers and strings, raises a TypeError in modern Python. Convert or normalize values when that matches your data’s meaning.

Case-insensitive text order

labels = {'A': 'zebra', 'B': 'Apple', 'C': 'mango'}
ordered = dict(
    sorted(labels.items(), key=lambda item: str(item[1]).lower())
)
# {'B': 'Apple', 'C': 'mango', 'A': 'zebra'}

Using str(...).lower() is appropriate only when converting every value to text is intentional. For locale-aware or human-language collation, use a collation strategy suited to your application rather than assuming lowercase is sufficient.

Missing or optional fields

For nested data, use dict.get() with a comparison-safe default when a field may be absent:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
records = {
    'one': {'score': 8},
    'two': {},
    'three': {'score': 3},
}

ordered = dict(
    sorted(records.items(), key=lambda item: item[1].get('score', 0))
)

Choose a default that places missing records where you actually want them. If missing data should be rejected, validate it first and let the error surface rather than silently assigning a misleading position.

Does sorting mutate the original dictionary?

No. sorted() creates a new list, and dict() creates a new dictionary. The source mapping remains unchanged:

data = {'b': 2, 'a': 3}
ordered = dict(sorted(data.items()))

print(data)     # {'b': 2, 'a': 3}
print(ordered)  # {'a': 3, 'b': 2}

You can deliberately replace the variable when you want the sorted result to become the working dictionary:

data = dict(sorted(data.items(), key=lambda item: item[1]))

This rebinds data; it does not reorder an existing dictionary object that another variable may still reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Insertion order in modern Python

Regular dictionaries guarantee insertion order in Python 3.7 and later. Consequently, a dictionary rebuilt from sorted pairs iterates and displays in that sorted sequence:

ordered = dict(sorted({'b': 2, 'a': 1}.items()))
print(list(ordered))
# ['a', 'b']

This is not a continuously self-sorting mapping. If you add a new key later, normal dictionary insertion rules apply and the new key is appended at that point:

ordered['aa'] = 99
print(list(ordered))
# ['a', 'b', 'aa']

Sort again whenever the data changes and consumers require a fresh global order.

Dictionary versus OrderedDict

For a newly sorted result on supported modern Python versions, a regular dict is usually enough. collections.OrderedDict remains useful when you target older Python versions or need its specialized operations, such as moving entries explicitly or comparing order-sensitive mappings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from collections import OrderedDict

ordered = OrderedDict(sorted(data.items(), key=lambda item: item[1]))

Do not choose OrderedDict merely because you want predictable iteration on Python 3.7 or newer; the built-in dictionary already provides that guarantee.

One-time iteration, rebuilt mapping, or top results?

Need Recommended expression Result
Process keys once for key in sorted(data): Sorted key iteration; source is untouched
Process pairs once for key, value in sorted(data.items(), key=...): Sorted pair iteration; no rebuilt dictionary
Keep an ordered snapshot dict(sorted(data.items(), key=...)) New insertion-ordered dictionary
Keep only a small number of results sorted(data.items(), key=...)[:n] List of the first n sorted pairs

Sorting the complete collection takes O(n log n) time and uses memory for the sorted list (and, when rebuilding, the new dictionary). If you only need a few extreme entries from a very large dataset, a heap-based approach can avoid a full sort, but it returns a different data structure and tie behavior must be specified separately.

Or skip the browser setup

If you are documenting sorted results or need screenshots of a page without configuring a headless browser, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed, while bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are reported and cost nothing.

It also includes an MCP server for AI agents such as Claude and Cursor, with take_screenshot, get_page_info, and capture_pdf tools. One thousand screenshots per month are free with no card; paid plans start at $5 for 3,000 shots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

See the complete option list and response headers in the ScreenshotNeo documentation. Create a free account at ScreenshotNeo sign-up to get 1,000 screenshots per month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common errors and fixes

AttributeError: 'dict' object has no attribute 'sort'

Dictionaries do not have a sort() method. Use sorted(data.items()) and rebuild with dict(), or iterate with sorted(data).

TypeError while comparing keys or values

Your comparison values are incompatible, commonly because strings and numbers are mixed. Normalize them deliberately, validate the input, or provide a key that extracts a consistently typed field.

Unexpected tie order

Equal comparison keys retain their original relative order. If that is not your policy, return a compound key such as (item[1], item[0]), or use the stable two-pass pattern for different directions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The result appears unsorted after adding entries

A dictionary does not maintain a sorted invariant. Re-run the sorting expression after mutations, or sort at the point where you produce output.

Nested-key lookup raises KeyError

Some records do not contain the requested field. Validate records first or use .get() with a documented default and confirm that the default has the intended sort position.

Practical checklist

  • Choose whether you need sorted keys, values, or a compound criterion.
  • Use sorted(); there is no built-in dict.sort().
  • Rebuild with dict() only when you need an ordered snapshot.
  • Add reverse=True for descending order.
  • Define a secondary key when equal values need deterministic ordering.
  • Normalize mixed or case-sensitive values before comparison.
  • Remember that later insertions do not preserve the previous global sort.
  • Use OrderedDict only for legacy compatibility or its specialized methods.

Frequently Asked Questions

What is the shortest way to sort a dictionary by value?

Use dict(sorted(data.items(), key=lambda item: item[1])) for ascending values.

How do I sort only the keys?

Use sorted(data), or loop with for key in sorted(data) when you do not need a rebuilt dictionary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Will assigning the sorted result back change other references to the old dictionary?

No. Reassignment points that variable at a new dictionary; references to the original object still see its original insertion order and contents.

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.