How to sort a dictionary in Python

Dictionaries store key-value pairs in Python, but their unordered nature can complicate data organization. Python provides multiple built-in methods and operators to sort dictionaries by keys, values, or both elements simultaneously.

This guide covers essential sorting techniques, practical examples, and troubleshooting tips. The code examples, created with Claude, an AI assistant built by Anthropic, demonstrate real-world dictionary sorting applications.

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)
{'apple': 1, 'banana': 3, 'kiwi': 4, 'orange': 2}

The sorted() function transforms the dictionary's unordered key-value pairs into an alphabetically sorted sequence based on the keys. When you pass data.items() to sorted(), Python compares dictionary keys using their natural ordering—alphabetical for strings and numerical for numbers.

Converting the sorted items back to a dictionary with dict() preserves the sorted order in Python 3.7+. This approach offers two key benefits:

  • Maintains data relationships between keys and values during sorting
  • Creates predictable, consistent output for data processing and display

Basic dictionary sorting techniques

Building on the sorted() function's capabilities, Python offers additional dictionary sorting patterns that give you precise control over how key-value data gets organized and processed.

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)
{'apple': 1, 'orange': 2, 'banana': 3, 'kiwi': 4}

The key=lambda item: item[1] parameter tells Python to sort dictionary items based on their values instead of keys. This creates a new dictionary where entries are ordered by ascending numeric values (1, 2, 3, 4) rather than alphabetically by keys.

  • The lambda function extracts each value using item[1] from the key-value pairs
  • Python uses these extracted values as sorting criteria
  • The original dictionary structure remains intact. Only the order changes

This technique proves especially useful when you need to rank or prioritize dictionary data based on numeric values. For example, sorting products by price or organizing player scores in a game.

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]}")
apple: 1
banana: 3
kiwi: 4
orange: 2

The sorted(fruits.keys()) method creates an alphabetically ordered list of dictionary keys, which the for loop then processes sequentially. This approach gives you direct control over the iteration order while maintaining access to both keys and values.

  • The keys() method extracts all dictionary keys into a list
  • Python sorts these keys alphabetically using sorted()
  • The f-string syntax (f"{key}: {fruits[key]}") efficiently formats each key-value pair for output

This pattern proves particularly useful when you need to process dictionary entries in a specific order while preserving the original data structure. The technique works consistently across different Python versions and dictionary sizes.

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)
{'hat': 15, 'shirt': 25, 'pants': 35, 'shoes': 45}

Dictionary comprehension offers a concise way to create sorted dictionaries in a single line. The sorted_by_keys expression creates a new dictionary by sorting the keys alphabetically, while sorted_by_values organizes entries based on their numeric values.

  • The k: prices[k] syntax maintains the connection between keys and their original values during sorting
  • Using lambda x: x[1] tells Python to sort based on the value component of each key-value pair
  • The output shows items arranged by ascending prices, from the $15 hat to the $45 shoes

This approach combines the power of dictionary comprehension with sorting functionality. It creates cleaner, more maintainable code compared to traditional loop-based sorting methods.

Advanced dictionary sorting methods

Building on Python's built-in sorting capabilities, advanced techniques like lambda functions, nested value handling, and itemgetter() unlock more sophisticated ways to organize complex dictionary data.

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)
{'David': (95, 'A'), 'Bob': (92, 'A'), 'Alice': (85, 'A'), 'Charlie': (78, 'B')}

The lambda function in this example enables multi-level sorting of student records based on two criteria: letter grades and numerical scores. The tuple (x[1][1], -x[1][0]) creates a compound sorting key that first groups students by their letter grade, then orders them by descending numerical scores within each grade group.

  • The first sorting criterion x[1][1] accesses the letter grade ('A' or 'B')
  • The second criterion -x[1][0] uses a negative sign to sort numerical scores in descending order
  • Python automatically sorts tuples element by element, enabling this elegant multi-level sorting approach

The output shows all 'A' students grouped together and sorted by their descending numerical scores (95, 92, 85), followed by 'B' students. This pattern proves particularly useful when organizing hierarchical data that requires multiple sorting levels.

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)
{'user2': {'name': 'Bob', 'score': 92, 'active': False}, 'user1': {'name': 'Alice', 'score': 85, 'active': True}, 'user3': {'name': 'Charlie', 'score': 78, 'active': True}}

When dictionaries contain nested data structures like in our users example, sorting requires accessing values within the inner dictionary. The lambda function extracts the 'score' value from each user's nested dictionary using x[1]['score'] as the sorting key.

  • The x[1] part accesses the inner dictionary containing user details
  • Adding reverse=True sorts users by descending scores instead of ascending
  • The output maintains the complete nested structure while reordering based on scores

This pattern works well for complex data structures where sorting criteria exist within nested dictionaries. The technique scales effectively for dictionaries containing multiple nested levels or different data types.

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)
{'laptop': 1200, 'phone': 800, 'tablet': 500, 'headphones': 150}

The itemgetter() function from Python's operator module provides a more efficient alternative to lambda functions when sorting dictionaries. It creates a callable object that retrieves the specified index or key from an iterable, making the sorting process faster and more readable.

  • The argument itemgetter(1) extracts values from key-value pairs while itemgetter(0) would extract keys
  • Adding reverse=True flips the sorting order from ascending to descending
  • This approach performs better than equivalent lambda functions, especially when sorting large dictionaries

In the example, itemgetter(1) sorts products by their prices. The output shows items arranged from highest price (laptop at 1200) to lowest (headphones at 150), demonstrating how itemgetter() elegantly handles numeric sorting.

Sorting financial transactions for monthly reports using lambda

Financial transaction data often requires chronological organization for accurate reporting, and Python's lambda functions enable precise sorting of nested dictionaries by date values while preserving transaction details.

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 demonstrates nested dictionary sorting and formatted output for financial data. The transactions dictionary stores transaction records with unique IDs as keys, containing dates and monetary amounts in nested dictionaries.

The sorting operation uses sorted() with a lambda function to organize transactions chronologically. The lambda x: x[1]['date'] expression tells Python to sort based on the date value within each nested dictionary. The items() method converts the dictionary into sortable pairs.

  • The for loop iterates through the sorted dictionary
  • F-string formatting (:.2f) ensures proper decimal display of amounts
  • The output presents each transaction with its date and dollar amount in chronological order

Creating a word frequency analyzer with sorted() and dictionaries

Dictionary sorting enables powerful text analysis capabilities, as demonstrated in this word frequency counter that uses sorted() with lambda functions to rank words by their occurrence count in descending order.

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 creates a word frequency counter that processes text in three key steps. First, it converts the input string to lowercase and removes periods using lower() and replace(), then splits it into individual words with split().

The core functionality uses a dictionary to track word occurrences. The get() method checks if a word exists in the dictionary. If not found, it returns 0 as the default value. Each time a word appears, its count increases by 1.

  • The sorted() function with lambda x: x[1] orders words by their frequency
  • Setting reverse=True displays most frequent words first
  • F-strings format the output as "word: count" pairs

Common errors and challenges

Python dictionary sorting can trigger unexpected errors and performance bottlenecks that require specific debugging strategies and optimization techniques to resolve effectively.

Fixing TypeError when sorting dictionaries with sorted()

When sorting dictionaries, Python's sorted() function can raise a TypeError if you try to access values from the sorted output directly. This common issue occurs because sorted() returns only the dictionary keys by default. The code below demonstrates this error in action.

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 sorted() function returns a list of keys instead of key-value pairs. When the code attempts to access the value using sorted_data[0][1], Python can't find the expected tuple structure. Let's examine the corrected approach 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 corrected code accesses dictionary values by using the original dictionary data with sorted keys instead of trying to extract values directly from sorted() output. This prevents the TypeError that occurs when attempting to treat sorted keys as key-value pairs.

Watch for this error when working with sorted dictionaries in these scenarios:

  • Iterating through sorted dictionary keys while needing access to values
  • Processing sorted dictionary data in loops or list comprehensions
  • Converting between dictionary views and sorted sequences

The solution maintains data integrity by keeping the original dictionary structure intact while allowing ordered access through the sorted keys list.

Handling missing keys when sorting nested dictionaries

Sorting nested dictionaries can fail when inner dictionaries lack expected keys. This common issue triggers KeyError exceptions when the sorting function attempts to access missing values. The code below demonstrates how a missing 'score' key disrupts the sorting operation.

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 lambda function attempts to access the 'score' key for each user, but user2 lacks this key. This triggers a KeyError exception, halting the sorting operation. Let's examine a robust solution that handles missing dictionary keys.

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 get() method provides a safer way to access dictionary values by returning a default value (0 in this case) when a key doesn't exist. This prevents the KeyError exception that would occur with direct key access using square brackets.

  • Watch for this error when sorting dictionaries with inconsistent data structures
  • Common in scenarios involving data from external sources or user input
  • The default value choice impacts the sorting order. Items with missing keys appear first when using 0

This pattern works especially well for data cleaning and normalization tasks where missing values are common. The solution maintains code reliability without compromising sorting functionality.

Optimizing multiple sorting operations on dictionaries

Repeatedly sorting and filtering dictionaries can create performance bottlenecks, especially with large datasets. The code below demonstrates how multiple sorted() operations within a loop impact efficiency when filtering dictionary items based on different thresholds.

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 code inefficiently sorts and filters the dictionary multiple times within the loop. Each iteration creates a new sorted dictionary and filters it. This approach wastes computational resources when processing large datasets. Let's examine a more efficient implementation.

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

Moving the sorted() operation outside the loop dramatically improves performance by sorting the dictionary only once. The sorted items remain available for all threshold checks instead of redundantly re-sorting on each iteration.

  • Watch for this pattern when processing dictionaries in loops
  • Pay special attention to data processing pipelines that combine sorting with filtering
  • Consider caching sorted results when working with large datasets or frequent access patterns

This optimization becomes particularly important when dealing with large dictionaries or when the sorting operation needs to happen frequently in your application's lifecycle.

FAQs

What is the difference between sorted() and using the 'sort' method on dictionaries?

The sorted() function creates a new sorted list from a dictionary's keys while the sort() method modifies a list in place. Since dictionaries are unordered collections, you can't directly sort them. Instead, sorted() returns their keys in a new sorted list, preserving the original dictionary.

When working with dictionaries, sorted() proves more versatile since it accepts optional parameters to sort by values instead of keys. This flexibility makes it the preferred choice for dictionary operations.

How do you sort a dictionary by its values instead of keys?

Python's sorted() function transforms dictionaries into sorted lists based on values. Pass your dictionary to sorted() with a key parameter that uses lambda to specify the sorting criteria. The dict.items() method provides key-value pairs for sorting.

  • For ascending order: sorted(dict.items(), key=lambda x: x[1])
  • For descending order, add reverse=True parameter

This approach works because sorted() expects an iterable input. The lambda function tells Python to sort based on the second element (value) instead of the first (key).

Can you sort a dictionary in descending order?

Python dictionaries don't maintain a fixed order by default, but you can sort them by converting to a list of items and using sorted() with a reverse parameter. The sorted() function returns a new sorted list while preserving the original dictionary.

  • Use dict.items() to get key-value pairs
  • Apply sorted() with reverse=True for descending order
  • Specify a key parameter to sort by values instead of keys

This approach creates a new sorted structure rather than modifying the original dictionary. This aligns with Python's philosophy of explicit operations over implicit ones.

What happens to the original dictionary when you use sorted()?

The sorted() function creates a new sorted list while leaving the original dictionary completely unchanged. This happens because sorted() works non-destructively—it takes the dictionary's keys as input but doesn't modify the source data structure.

Here's what actually occurs:

  • Python creates a new list containing the dictionary's keys
  • The function sorts this new list
  • Your original dictionary maintains its order and content
  • You receive a sorted list as the return value

How do you sort a dictionary by both keys and values at the same time?

Python's sorted() function accepts a dictionary and returns a sorted list of tuples. To sort by both keys and values simultaneously, pass a lambda function to the key parameter that returns a tuple of the elements you want to sort by. The sorting happens in order—first by the initial element, then by subsequent elements when there are ties.

For example, sorted(my_dict.items(), key=lambda x: (x[0], x[1])) sorts first by keys then values. This works because Python compares tuples element by element, making it perfect for multi-level sorting.

🏠