DEV Community

Mohammad Nadeem
Mohammad Nadeem

Posted on

Custom Sorting in Python: Lists and Dictionaries Demystified

Sorting data in Python is easy with sorted(), but what if you want to sort by custom logic? In this post, weโ€™ll explore how to sort lists and dictionaries in Python using custom keys and lambda functions.

๐Ÿ”ข Sorting Lists in Python

โœ… Default List Sorting

numbers = [5, 2, 9, 1]
print(sorted(numbers))  # [1, 2, 5, 9]
Enter fullscreen mode Exit fullscreen mode

This works great for simple data. But what about sorting by length, reverse order, or object properties?

๐Ÿง  Custom Sorting with key=
1. Sort strings by length

words = ['banana', 'apple', 'kiwi', 'strawberry']
sorted_by_length = sorted(words, key=len)
print(sorted_by_length)
# ['kiwi', 'apple', 'banana', 'strawberry']
Enter fullscreen mode Exit fullscreen mode

2. Sort strings by last character

sorted_by_last_char = sorted(words, key=lambda x: x[-1])
print(sorted_by_last_char)
# ['banana', 'kiwi', 'apple', 'strawberry']
Enter fullscreen mode Exit fullscreen mode

3. Sort a list of tuples by second value

pairs = [(1, 3), (2, 2), (4, 1)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)
# [(4, 1), (2, 2), (1, 3)]
Enter fullscreen mode Exit fullscreen mode

๐Ÿงฐ Sorting Lists of Dicts
This is common in APIs or tabular data:

users = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ฝ Sort by age:

sorted_users = sorted(users, key=lambda x: x['age'])
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ผ Sort by name (descending):

sorted_users = sorted(users, key=lambda x: x['name'], reverse=True)
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Sorting Dictionaries by Keys or Values
By default, dictionaries in Python 3.7+ maintain insertion order. But we can sort them for display or processing.

scores = {'Alice': 82, 'Bob': 91, 'Charlie': 78}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ค Sort by key:

sorted_by_key = dict(sorted(scores.items()))
# {'Alice': 82, 'Bob': 91, 'Charlie': 78}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ข Sort by value:

sorted_by_value = dict(sorted(scores.items(), key=lambda item: item[1]))
# {'Charlie': 78, 'Alice': 82, 'Bob': 91}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”„ In-Place Sorting with .sort()
If you want to sort a list in-place (not return a new one):

numbers = [4, 1, 3]
numbers.sort()
print(numbers)  # [1, 3, 4]
Enter fullscreen mode Exit fullscreen mode

With custom key:

words.sort(key=lambda x: len(x))
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ .sort() works only on lists, not on dict or tuple.

โš™๏ธ Pro Tip: Use operator.itemgetter for cleaner syntax
from operator import itemgetter

sorted_users = sorted(users, key=itemgetter('age'))
Enter fullscreen mode Exit fullscreen mode

Works well when sorting by multiple keys too:

sorted_users = sorted(users, key=itemgetter('age', 'name'))
Enter fullscreen mode Exit fullscreen mode

โœจ Final Thoughts
Mastering custom sorting in Python helps you handle data more efficiently โ€” especially when working with APIs, CSVs, or databases. Whether youโ€™re sorting by value, custom rules, or multiple fields, Python gives you all the tools you need.

๐Ÿš€ Next up?
In the next post, Iโ€™ll dive into:

  • Sorting with multiple criteria
  • Using functools.cmp_to_key
  • Performance tips when sorting large datasets

Follow for more Python tricks, clean code tips, and backend dev guides! ๐Ÿ๐Ÿ’ป

Top comments (0)