How to sort a dictionary in Python

Learn how to sort a Python dictionary by key or value. Explore different methods, real-world examples, and common debugging tips.

How to sort a dictionary in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Python dictionaries are inherently unordered, but you often need to sort them by key or value. The built-in sorted() function makes this a straightforward and flexible process for any developer.

You'll explore several techniques to sort dictionaries, complete with practical examples. You'll also find real-world applications, performance tips, and advice to debug common issues you might face.

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}

The key to this method is applying the sorted() function to the dictionary's key-value pairs, which you get using the .items() method. This creates a list of tuples, where each tuple is a (key, value) pair.

By default, sorted() organizes these tuples based on their first element—the dictionary key. The dict() constructor then takes this sorted list of tuples and rebuilds it into a new dictionary, now ordered alphabetically by key.

Basic dictionary sorting techniques

Sorting by keys is just the start—you can also sort by values, iterate over the sorted dictionary, and use comprehensions for more concise code.

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 values, you'll use the key parameter within the sorted() function. This lets you specify exactly what part of each item to use for comparison.

  • A lambda function creates a short, anonymous function on the fly.
  • The expression lambda item: item[1] tells sorted() to use the second element of each tuple—the value—as the sort key.

The function then arranges the key-value pairs based on these values. The final dictionary is rebuilt with its items ordered numerically from smallest to largest value.

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

If you just need to process a dictionary in order, you don't have to create a new one. This method is more memory-efficient since it avoids building an entirely new dictionary.

  • First, sorted(fruits.keys()) generates a temporary list of the dictionary's keys, sorted alphabetically.
  • The for loop then iterates through this sorted list of keys.
  • Inside the loop, you can access the original dictionary's values in a predictable, sorted order.

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 let you build a new, sorted dictionary in a single line. It's a concise and Pythonic way to combine the sorting logic and dictionary creation you've already seen.

  • The expression {k: prices[k] for k in sorted(prices)} iterates over sorted keys to build a key-sorted dictionary.
  • Similarly, you can sort by value using a lambda function on the items, creating the dictionary in one go.

Advanced dictionary sorting methods

Beyond simple sorting, you can handle more intricate scenarios by implementing custom logic with lambda, sorting nested data, and boosting efficiency with 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 handle multi-level sorting by having your lambda function return a tuple. Python sorts by the first element in the tuple, then uses subsequent elements to break any ties.

  • The first element, x[1][1], sorts the students by grade alphabetically.
  • The second element, -x[1][0], sorts students with the same grade by their score. The negative sign cleverly reverses the sort order, arranging scores from highest to lowest.

This technique gives you a dictionary sorted first by grade, then by score in descending order.

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 with precision. The lambda function is flexible enough to reach into these nested structures. You just need to specify the path to the value you want to sort by.

  • The expression lambda x: x[1]['score'] tells sorted() to look at each item's value (x[1]), which is a nested dictionary, and then grab the value associated with the 'score' key.
  • Setting reverse=True flips the sort order, arranging the users from the highest score to the 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 efficient alternative to lambda, you can use itemgetter() from Python's operator module. It's a specialized tool that often performs better because its core logic is implemented in C, making it faster for simple data retrieval.

  • The expression itemgetter(1) creates a function that grabs the element at index 1 from each (key, value) tuple.
  • This function is then used as the sort key, telling sorted() to organize the dictionary items based on their values.

While a lambda offers more flexibility for complex logic, itemgetter() is the go-to choice for straightforward, performance-sensitive sorting.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. With Agent 4, you can move from learning individual techniques to building complete applications directly from a description.

Instead of piecing together sorting functions, you can describe the final application you want to build:

  • A real-time leaderboard that ranks players by score in descending order.
  • An inventory dashboard that organizes products alphabetically or by price.
  • A customer support tool that sorts tickets by priority and then by date.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Sorting dictionaries is powerful, but you might run into a few common pitfalls like type mismatches, missing keys, or performance bottlenecks.

Fixing TypeError when sorting dictionaries with sorted()

A TypeError often pops up when you try to sort a dictionary whose keys or values contain mixed data types, like strings and integers. Python's sorted() function doesn't know how to compare fundamentally different things, such as the number 10 and the word 'ten'.

To fix this, you can provide a key function that converts all items to a single, comparable type before sorting. For example, using key=str tells Python to treat every item as a string during the sort, ensuring a consistent comparison and preventing the error.

Handling missing keys when sorting nested dictionaries

When sorting a dictionary of dictionaries, you'll hit a KeyError if your sort key doesn't exist in every nested dictionary. This is a common issue when your data is inconsistent—for instance, some users might have a 'last_login' field while others don't.

The best way to handle this is to use the .get() method within your lambda function. By providing a default value, like lambda item: item[1].get('score', 0), you tell Python to use 0 if the 'score' key is missing. This prevents the program from crashing and ensures every item can be sorted reliably.

Optimizing multiple sorting operations on dictionaries

Repeatedly sorting a large dictionary can be a drag on performance, especially if you're doing it inside a loop. Calling the sorted() function over and over again forces Python to re-evaluate and re-order the entire dataset each time.

If you need to access the data in a specific order multiple times, a more efficient approach is to sort it once and store the result. Create a new sorted dictionary or a list of sorted items and reuse that variable for all subsequent operations. This avoids redundant processing and makes your code run much faster.

Fixing TypeError when sorting dictionaries with sorted()

Another common TypeError stems from a misunderstanding of what sorted() returns. When you sort a dictionary directly, you get a list of its keys, not key-value pairs. Trying to access a value from this list will cause an error, as the code below demonstrates.

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 code fails because it treats the sorted key, a string, as if it were a key-value tuple. The expression sorted_data[0][1] then attempts to index that string, triggering a TypeError. The example below shows the correct approach.

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 fix is to use the sorted list of keys to look up values in the original dictionary. The sorted() function, when applied directly to a dictionary, returns only a list of its keys. To get a value, you must take a key from that sorted list and use it to access the original dictionary, like data[sorted_keys[0]]. This is a common pitfall when you only need to iterate, not create a new sorted dictionary.

Handling missing keys when sorting nested dictionaries

Handling missing keys when sorting nested dictionaries

When sorting nested dictionaries, your code is only as reliable as your data. If a sort key is missing from even one dictionary, your program will crash with a KeyError. This often happens when you're dealing with inconsistent datasets.

The code below demonstrates this exact scenario. Notice how one user is missing the 'score' key, which causes the entire sort operation to fail.

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 sort fails because the lambda function expects a 'score' key in every user's dictionary. When it reaches 'user2', which is missing that key, a KeyError is triggered. The corrected approach is shown below.

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 fix is to use the dictionary’s .get() method within your lambda function. By writing lambda x: x[1].get('score', 0), you're telling Python to use a default value of 0 whenever the 'score' key is not found. This simple change prevents the KeyError and ensures every item can be sorted reliably. You'll find this technique essential when working with data from APIs or user inputs, where consistency isn't always guaranteed.

Optimizing multiple sorting operations on dictionaries

Repeatedly sorting a large dictionary, especially inside a loop, can seriously slow down your code. Each time you call sorted(), Python has to re-process the entire dataset, and this redundant work adds up quickly. The code below demonstrates this inefficiency in action.

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 inefficiency comes from calling sorted() inside the loop. With each iteration, the code re-sorts the entire dictionary from scratch, even though the underlying data remains the same. See how a simple change fixes this.

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 call the sorted() function just once before the loop begins. By storing the sorted items in a variable, you avoid the costly process of re-sorting the same data with every iteration. This simple change makes your code much more efficient, especially with large datasets. Keep an eye out for this pattern whenever you're performing repeated operations on data that needs to be in a specific order.

Real-world applications

With these sorting techniques and troubleshooting skills, you're ready to tackle real-world challenges like financial reporting and text analysis.

Sorting financial transactions for monthly reports using lambda

You can use a lambda function to sort a dictionary of financial transactions chronologically, which is essential for generating organized 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 example organizes financial records by date. The key is the lambda function, which tells sorted() exactly what to compare.

  • The expression lambda x: x[1]['date'] instructs the sort to look inside each transaction's nested dictionary (x[1]) and use the 'date' string as the basis for ordering.
  • Since the dates are in a standard YYYY-MM-DD format, a simple alphabetical sort correctly arranges them from earliest to latest.

The final loop then prints the formatted results in chronological order.

Creating a word frequency analyzer with sorted() and dictionaries

Another practical application is building a word frequency analyzer, where you use a dictionary to tally words and sorted() to rank them by count.

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 first processes a raw string into a clean list of words using .lower(), .replace(), and .split(). It then builds a frequency map by iterating through the words and tallying each one. This approach demonstrates how vibe coding can help you rapidly prototype text analysis tools.

  • The .get(word, 0) method is the key to this process—it safely increments a word's count or initializes it if the word is new.
  • Finally, sorted() with a lambda function and reverse=True organizes the dictionary's items by count, from most to least frequent, before printing the final ranked list.

Get started with Replit

Turn your knowledge into a real tool. Describe what you want, like "a word frequency analyzer that ranks words by count" or "an inventory app that sorts products by price," and let Replit Agent handle it.

Replit Agent writes the code, tests for errors, and deploys your application, letting you focus on the idea. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.