October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Sort a Dictionary in Python by Key or Value

Use sorted() for dictionary keys, or sort d.items() by each value to build a new dictionary in value order.

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.

Use sorted(d) to get a list of a dictionary’s keys in ascending order. To build a new dictionary in key order, use {key: d[key] for key in sorted(d)}. To build one ordered by values, sort the key-value pairs with dict(sorted(d.items(), key=lambda item: item[1])). Add reverse=True for descending order.

Sort a dictionary by key

Passing a dictionary to sorted() sorts its keys and returns a list, not a dictionary:

scores = {"Mina": 91, "Dev": 78, "Alex": 91}

keys = sorted(scores)
print(keys)  # ['Alex', 'Dev', 'Mina']

If you need a mapping whose entries are inserted in key order, create a new dictionary from that key list:

by_key = {key: scores[key] for key in sorted(scores)}
print(by_key)  # {'Alex': 91, 'Dev': 78, 'Mina': 91}

Python dictionaries preserve insertion order, so iterating over by_key follows the order in which the sorted keys were inserted. This guarantee applies from Python 3.7 onward; it preserves insertion order but does not sort a dictionary automatically. Python’s built-in types documentation describes dictionary ordering.

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.

Sort a dictionary by value

Use items() to get key-value pairs, and set the sort key to the value at index 1. Wrap the result in dict() to produce a new dictionary:

by_value = dict(sorted(scores.items(), key=lambda item: item[1]))
print(by_value)  # {'Dev': 78, 'Mina': 91, 'Alex': 91}

To sort from highest value to lowest, pass reverse=True:

by_value_desc = dict(
    sorted(scores.items(), key=lambda item: item[1], reverse=True)
)

sorted() returns a new list of sorted items; it does not rearrange the original dictionary in place. Building a new dictionary from those items gives you a mapping with the sorted insertion sequence.

Choose how ties are ordered

Python’s sort is stable: pairs with equal sort values keep their relative order from the input items. If you want an explicit secondary rule, include it in a tuple key. This example sorts by value, then by key:

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

The secondary key works when the values and keys being compared have compatible ordering. For a concise value key, you can use operator.itemgetter(1) instead of a lambda:

from operator import itemgetter

by_value = dict(sorted(scores.items(), key=itemgetter(1)))

The Python Sorting HOW TO documents stable sorting, tuple-based sort keys, and itemgetter().

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

Handle text and values that cannot be compared

  • Case-insensitive text keys: use key=str.casefold, for example sorted(names, key=str.casefold). This normalizes case for comparison; it is not locale-aware alphabetical sorting.
  • Locale-aware text: use locale.strxfrm() or locale.strcoll() when the desired ordering depends on the active locale.
  • Mixed or special values: values of incompatible types may raise TypeError when Python tries to compare them. None cannot be ordered against ordinary numbers, and NaN values do not participate in ordinary numeric ordering consistently. Define a deliberate key or handle these values separately.
  • String conversion: converting mixed values to strings can make them sortable, but the result is lexical rather than necessarily numeric; for example, text ordering may not match numeric ordering.

The sorting guide covers sort keys and special comparison cases.

Quick reference

Goal Code Result
Get keys in ascending order sorted(d) A list of keys
Create a dictionary in ascending key order {k: d[k] for k in sorted(d)} A new dictionary
Create a dictionary in ascending value order dict(sorted(d.items(), key=lambda item: item[1])) A new dictionary
Sort values in descending order dict(sorted(d.items(), key=lambda item: item[1], reverse=True)) A new dictionary, highest value first

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.