How to Sort a Dictionary by Kth Index Value in Python?

In Python, we can sort a dictionary by the value of a specific index (kth index value) using various approaches like the sorted() function with lambda, itemgetter() from the operator module, or custom functions. Let's explore these methods with practical examples.

Method 1: Using sorted() with Lambda Function

This method uses the sorted() function with a lambda function to specify the sorting criterion based on the kth index value.

Syntax

sorted_dict = dict(sorted(dictionary.items(), key=lambda x: x[1][k]))

Example

Here we sort a dictionary by the second element (index 1) of each list value ?

# Dictionary with lists as values
fruits = {'apple': ['red', 50, 'sweet'], 
          'banana': ['yellow', 30, 'sweet'], 
          'orange': ['orange', 40, 'citrus']}

# Sort by index 1 (quantity)
k = 1
sorted_fruits = dict(sorted(fruits.items(), key=lambda x: x[1][k]))
print("Sorted by quantity:")
print(sorted_fruits)
Sorted by quantity:
{'banana': ['yellow', 30, 'sweet'], 'orange': ['orange', 40, 'citrus'], 'apple': ['red', 50, 'sweet']}

Method 2: Using itemgetter() from operator Module

The itemgetter() function provides a more readable and efficient approach for accessing nested elements.

Syntax

from operator import itemgetter
sorted_dict = dict(sorted(dictionary.items(), key=itemgetter(1)))

Example

Using itemgetter() to sort by the kth index value ?

from operator import itemgetter

# Dictionary with tuple values
students = {'john': (85, 'A', 'math'), 
           'alice': (92, 'A+', 'physics'), 
           'bob': (78, 'B', 'chemistry')}

# Sort by index 0 (score)
k = 0
sorted_students = dict(sorted(students.items(), key=lambda x: x[1][k]))
print("Sorted by score:")
print(sorted_students)

# For direct tuple sorting, we can also use:
sorted_students_alt = dict(sorted(students.items(), key=itemgetter(1)))
print("\nUsing itemgetter on entire tuple:")
print(sorted_students_alt)
Sorted by score:
{'bob': (78, 'B', 'chemistry'), 'john': (85, 'A', 'math'), 'alice': (92, 'A+', 'physics')}

Using itemgetter on entire tuple:
{'bob': (78, 'B', 'chemistry'), 'john': (85, 'A', 'math'), 'alice': (92, 'A+', 'physics')}

Method 3: Using a Custom Function

Creating a reusable function provides modularity and makes the code more maintainable.

Syntax

def sort_dict_by_kth_index(dictionary, k, reverse=False):
    return dict(sorted(dictionary.items(), key=lambda x: x[1][k], reverse=reverse))

Example

Defining a custom function with additional features like reverse sorting ?

def sort_dict_by_kth_index(dictionary, k, reverse=False):
    """Sort dictionary by kth index of values"""
    return dict(sorted(dictionary.items(), key=lambda x: x[1][k], reverse=reverse))

# Dictionary with nested data
products = {'laptop': [1200, 'electronics', 4.5], 
           'phone': [800, 'electronics', 4.2], 
           'book': [25, 'education', 4.8]}

# Sort by price (index 0) - ascending
print("Sorted by price (ascending):")
sorted_by_price = sort_dict_by_kth_index(products, 0)
print(sorted_by_price)

# Sort by rating (index 2) - descending
print("\nSorted by rating (descending):")
sorted_by_rating = sort_dict_by_kth_index(products, 2, reverse=True)
print(sorted_by_rating)
Sorted by price (ascending):
{'book': [25, 'education', 4.8], 'phone': [800, 'electronics', 4.2], 'laptop': [1200, 'electronics', 4.5]}

Sorted by rating (descending):
{'book': [25, 'education', 4.8], 'laptop': [1200, 'electronics', 4.5], 'phone': [800, 'electronics', 4.2]}

Comparison

Method Readability Performance Best For
Lambda function Good Fast Simple one-time sorting
itemgetter() Excellent Fastest When sorting by entire nested structure
Custom function Excellent Fast Reusable logic, complex requirements

Conclusion

Use lambda functions for quick sorting by kth index. Choose itemgetter() for better performance and readability. Create custom functions when you need reusable sorting logic with additional features like reverse ordering.

Updated on: 2026-03-27T08:45:52+05:30

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements