How to sort a dictionary in Python

Learn how to sort a Python dictionary by key or value. This guide covers methods, tips, real-world uses, and common error debugging.

How to sort a dictionary in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Tue
Feb 10, 2026
The Replit Team Logo Image
The Replit Team

Developers often need to sort dictionaries in Python, a task complicated by their historically unordered nature. Since Python 3.7, dictionaries maintain insertion order, which makes the process more predictable.

You'll explore techniques to sort by key or value with functions like sorted(). You'll also find real-world applications, practical tips, and debugging advice to handle dictionary manipulation effectively.

Using the sorted() function with dictionary keys

data = {'banana': 3, 'apple': 1, 'orange': 2, 'kiwi': 4}
sorted_dict = dict(sorted(data.items()))
print(sorted_dict)--OUTPUT--{'apple': 1, 'banana': 3, 'kiwi': 4, 'orange': 2}

This approach chains a few methods together to achieve the sort. The data.items() method first converts the dictionary into an iterable of (key, value) tuples. This prepares the data for the sorted() function.

The sorted() function then gets to work. When given a list of tuples, it defaults to sorting by the first item in each tuple—in this case, the dictionary key. The final dict() call reconstructs the dictionary from these sorted pairs, resulting in a new dictionary ordered alphabetically by its keys.

Basic dictionary sorting techniques

While sorting by keys is useful, you can gain more control by sorting by values, iterating through the dictionary, or using a dictionary comprehension.

Sorting a dictionary by values

data = {'banana': 3, 'apple': 1, 'orange': 2, 'kiwi': 4}
sorted_by_value = dict(sorted(data.items(), key=lambda item: item[1]))
print(sorted_by_value)--OUTPUT--{'apple': 1, 'orange': 2, 'banana': 3, 'kiwi': 4}

To sort by value, you introduce the key argument to the sorted() function. This argument lets you specify exactly what part of each item to use for the sorting comparison.

  • A lambda function provides a quick, inline way to define this logic without writing a full function.
  • The expression lambda item: item[1] tells sorted() to look at the second element of each (key, value) tuple—which is the value—and use it for sorting.

The rest of the process works the same, giving you a new dictionary ordered by its values.

Iterating through a sorted dictionary

fruits = {'banana': 3, 'apple': 1, 'orange': 2, 'kiwi': 4}
for key in sorted(fruits.keys()):
print(f"{key}: {fruits[key]}")--OUTPUT--apple: 1
banana: 3
kiwi: 4
orange: 2

Sometimes you don't need to create a new sorted dictionary; you just need to process the existing one in order. This approach is more direct and memory-efficient if you're only iterating once.

  • The sorted() function is applied directly to fruits.keys(), which creates a temporary, sorted list of the dictionary's keys.
  • The for loop then iterates over this sorted list. Inside the loop, you use each key to look up its value in the original fruits dictionary.

This lets you access and use the dictionary's data in alphabetical key order without modifying the dictionary itself.

Using dictionary comprehension for sorted results

prices = {'shirt': 25, 'pants': 35, 'hat': 15, 'shoes': 45}
sorted_by_keys = {k: prices[k] for k in sorted(prices)}
sorted_by_values = {k: v for k, v in sorted(prices.items(), key=lambda x: x[1])}
print(sorted_by_values)--OUTPUT--{'hat': 15, 'shirt': 25, 'pants': 35, 'shoes': 45}

Dictionary comprehensions offer a concise, Pythonic way to create a new dictionary. This syntax lets you build a sorted dictionary in a single, readable line by combining the loop and the creation process.

  • To sort by keys, the comprehension {k: prices[k] for k in sorted(prices)} iterates through the sorted keys and reconstructs the dictionary.
  • For sorting by values, {k: v for k, v in sorted(prices.items(), key=lambda x: x[1])} iterates over the sorted (key, value) pairs to build the final result.

Advanced dictionary sorting methods

Beyond basic key and value sorting, you can implement custom logic with lambda, handle nested dictionaries, and optimize performance with functions like itemgetter().

Implementing custom sort logic with lambda functions

students = {'Alice': (85, 'A'), 'Bob': (92, 'A'), 'Charlie': (78, 'B'), 'David': (95, 'A')}
by_grade_then_score = dict(sorted(students.items(),
key=lambda x: (x[1][1], -x[1][0])))
print(by_grade_then_score)--OUTPUT--{'David': (95, 'A'), 'Bob': (92, 'A'), 'Alice': (85, 'A'), 'Charlie': (78, 'B')}

You can sort by multiple criteria by having your lambda function return a tuple. Python sorts based on the first element in the tuple, then uses subsequent elements as tie-breakers for any items that are still equal.

  • The first criterion, x[1][1], sorts the students by their letter grade in ascending order, so 'A' comes before 'B'.
  • For students with the same grade, the second criterion, -x[1][0], sorts them by score. The negative sign cleverly reverses the default ascending sort, placing higher scores first.

Sorting dictionaries with nested values

users = {
'user1': {'name': 'Alice', 'score': 85, 'active': True},
'user2': {'name': 'Bob', 'score': 92, 'active': False},
'user3': {'name': 'Charlie', 'score': 78, 'active': True}
}
sorted_users = dict(sorted(users.items(), key=lambda x: x[1]['score'], reverse=True))
print(sorted_users)--OUTPUT--{'user2': {'name': 'Bob', 'score': 92, 'active': False}, 'user1': {'name': 'Alice', 'score': 85, 'active': True}, 'user3': {'name': 'Charlie', 'score': 78, 'active': True}}

When your dictionary's values are themselves dictionaries, you can still sort by a nested key. Your lambda function just needs to access the value of the outer dictionary item and then grab the key within that nested dictionary.

  • The expression lambda x: x[1]['score'] tells sorted() to look at each item, access the nested dictionary at index 1, and then pull the value associated with the 'score' key.
  • Adding reverse=True flips the sort order to descending, which is perfect for ranking things like scores from highest to lowest.

Using itemgetter() for efficient sorting

from operator import itemgetter
products = {'laptop': 1200, 'phone': 800, 'tablet': 500, 'headphones': 150}
by_price_ascending = dict(sorted(products.items(), key=itemgetter(1)))
by_price_descending = dict(sorted(products.items(), key=itemgetter(1), reverse=True))
print(by_price_descending)--OUTPUT--{'laptop': 1200, 'phone': 800, 'tablet': 500, 'headphones': 150}

For a more optimized approach, you can use itemgetter() from the operator module. It often performs better than a lambda function for simple lookups because it's implemented in C, making it a faster alternative.

  • The function itemgetter(1) creates a callable that fetches the second item—the value—from each (key, value) tuple.
  • This tells sorted() to use the dictionary's values for comparison, achieving the same result as lambda item: item[1].

You can still add reverse=True to sort in descending order, making this a clean and efficient way to handle simple sorting tasks.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the dictionary sorting techniques we've explored, Replit Agent can turn them into production tools:

  • A real-time leaderboard that ranks players by score.
  • A product catalog management tool that organizes items alphabetically.
  • A data analysis dashboard that sorts user data by multiple criteria, like activity status and then username.

Describe your app idea, and Replit Agent writes the code, tests it, and deploys it for you. Turn your concepts into working software without leaving your browser.

Common errors and challenges

Sorting dictionaries can be tricky; you might encounter type errors, missing keys in nested data, or performance issues with large datasets.

A TypeError is a common roadblock when your dictionary contains values of mixed data types, like integers and strings. Python's sorted() function throws this error because it doesn't know how to compare two fundamentally different things—is 5 greater or less than 'apple'?

  • To fix this, you need to give Python a consistent basis for comparison.
  • A simple solution is to use a lambda function in your key argument to convert all values to a single type, such as a string, before sorting. This ensures every comparison is valid.

When sorting nested dictionaries, you'll hit a KeyError if a key you're sorting by doesn't exist in every nested dictionary. The sort operation fails because it can't find a value to compare for the incomplete item.

  • The most reliable way to handle this is with the dictionary's get() method.
  • Instead of accessing a key directly, use item.get('score', 0). This provides a default value—like 0 or None—if the key is missing, preventing the error and allowing the sort to continue.

Repeatedly sorting a large dictionary on different criteria is inefficient. Each call to sorted() processes the entire dictionary from scratch, which can create performance bottlenecks in your application, especially with large datasets.

  • Instead of sorting multiple times, perform a single, multi-level sort.
  • You can achieve this by having your key function return a tuple with your sorting criteria in order of priority, like (primary_criterion, secondary_criterion). Python sorts by the first element and uses subsequent elements as tie-breakers, accomplishing a complex sort in one efficient pass.

Fixing TypeError when sorting dictionaries with sorted()

A common TypeError occurs when you apply sorted() directly to a dictionary. This action returns only a list of keys, not the full items. If you then try to access a value from this list as if it were a tuple, you’ll trigger an error. The code below shows this pitfall.

data = {'banana': 3, 'apple': 1, 'orange': 2}
sorted_data = sorted(data)
print(f"Keys: {sorted_data}")
print(f"Values for first key: {sorted_data[0][1]}") # Error!

The expression sorted_data[0][1] causes a TypeError because sorted_data is a list of strings, not (key, value) pairs. The code attempts to index a string as if it were a tuple. See the correct implementation below.

data = {'banana': 3, 'apple': 1, 'orange': 2}
sorted_keys = sorted(data)
print(f"Keys: {sorted_keys}")
print(f"Values for first key: {data[sorted_keys[0]]}")

The solution is to use the sorted list of keys to look up values in the original dictionary. The expression data[sorted_keys[0]] correctly retrieves the value for the first key in the sorted list, avoiding the error.

This pitfall is common when you intend to work with key-value pairs but forget to call .items(). Always use sorted(data.items()) when you need to sort by value or otherwise keep the pairs intact during the operation.

Handling missing keys when sorting nested dictionaries

Handling missing keys when sorting nested dictionaries

When sorting nested dictionaries, you'll get a KeyError if the sort key is missing from any item. This is common with inconsistent data, like a user record without a 'score'. The following code triggers this exact error.

users = {
'user1': {'name': 'Alice', 'score': 85},
'user2': {'name': 'Bob'}, # Missing 'score' key
'user3': {'name': 'Charlie', 'score': 78}
}
sorted_users = dict(sorted(users.items(), key=lambda x: x[1]['score']))

The expression lambda x: x[1]['score'] demands a 'score' key from every item. The sort operation stops with a KeyError when it encounters 'user2', which doesn't have one. The following code demonstrates a safer approach.

users = {
'user1': {'name': 'Alice', 'score': 85},
'user2': {'name': 'Bob'}, # Missing 'score' key
'user3': {'name': 'Charlie', 'score': 78}
}
sorted_users = dict(sorted(users.items(), key=lambda x: x[1].get('score', 0)))

The solution is to use the dictionary’s get() method. The expression lambda x: x[1].get('score', 0) safely retrieves the score. If the 'score' key is missing, it returns a default value of 0 instead of raising a KeyError. This ensures the sort operation can handle incomplete records without crashing. You'll find this technique essential when working with real-world data, which is often inconsistent or has missing fields.

Optimizing multiple sorting operations on dictionaries

Optimizing multiple sorting operations on dictionaries

Sorting a dictionary inside a loop is a classic performance bottleneck. Each iteration re-sorts the entire dataset from scratch, which wastes processing power, especially with large dictionaries. The following code illustrates this inefficiency by repeatedly sorting and filtering the same data.

data = {'banana': 3, 'apple': 1, 'orange': 2, 'kiwi': 4}
for threshold in range(1, 5):
filtered = dict(sorted(data.items(), key=lambda x: x[1]))
result = {k: v for k, v in filtered.items() if v > threshold}
print(f"Items > {threshold}: {result}")

The sorted() function runs inside the for loop, repeatedly re-sorting the same data. This creates unnecessary work in each iteration, which can significantly slow down the code. The code below demonstrates a more efficient approach.

data = {'banana': 3, 'apple': 1, 'orange': 2, 'kiwi': 4}
sorted_once = sorted(data.items(), key=lambda x: x[1])
for threshold in range(1, 5):
result = {k: v for k, v in sorted_once if v > threshold}
print(f"Items > {threshold}: {result}")

The solution is to sort the dictionary just once, before the loop begins. By moving the sorted() call outside the loop and storing its result in a variable like sorted_once, you avoid redundant processing.

  • The loop then works with this pre-sorted list for filtering.
  • This is crucial for performance, especially when you're working with large datasets.

Always watch for sorting operations inside loops, as they can be a hidden drain on efficiency.

Real-world applications

Now that you can navigate common errors, you can apply these sorting techniques to real-world tasks like financial reporting and text analysis.

Sorting financial transactions for monthly reports using lambda

You can use a lambda function to organize financial transactions chronologically, which is essential for creating clear and accurate monthly reports.

transactions = {
'tx001': {'date': '2023-05-15', 'amount': 250.50},
'tx002': {'date': '2023-05-05', 'amount': -120.75},
'tx003': {'date': '2023-05-20', 'amount': -45.00},
'tx004': {'date': '2023-05-02', 'amount': 1000.00}
}

# Sort transactions by date for a financial report
sorted_by_date = dict(sorted(transactions.items(), key=lambda x: x[1]['date']))
for tx_id, details in sorted_by_date.items():
print(f"{details['date']} - ${details['amount']:.2f}")

This code organizes a dictionary of financial records by date to prepare them for a report. The key is the sorted() function, which is guided by a lambda to pinpoint the exact data for comparison.

  • The transactions.items() method first breaks the dictionary into a list of (ID, details) pairs.
  • A lambda function then tells sorted() to use the 'date' from each transaction's details for the sort.
  • Finally, dict() rebuilds the dictionary from the newly ordered pairs, creating a chronological record ready for display.

Creating a word frequency analyzer with sorted() and dictionaries

You can build a simple word frequency analyzer by using a dictionary to count words and the sorted() function to rank them by popularity.

text = "Python is popular. Python is powerful. Programming in Python is enjoyable."
words = text.lower().replace('.', '').split()

# Build and sort a word frequency dictionary
word_freq = {}
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1

sorted_freq = dict(sorted(word_freq.items(), key=lambda x: x[1], reverse=True))
for word, count in sorted_freq.items():
print(f"{word}: {count}")

This code snippet first prepares the text for analysis by converting it to lowercase and splitting it into a list of individual words. It then builds a frequency map using a dictionary. The for loop uses the get() method to safely increment the count for each word, avoiding errors for words it hasn't seen yet.

  • The dictionary’s items are sorted based on the count—the second value in each pair.
  • Using reverse=True ensures the words are ranked from most to least frequent.
  • The result is a new dictionary that preserves this ranked order.

Get started with Replit

Turn these sorting techniques into a real application. Describe your idea to Replit Agent, like: "a leaderboard API that ranks players by score" or "a tool that creates a word frequency list from a text file".

Replit Agent writes the code, tests for errors, and deploys the app for you. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.