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]
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']
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']
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)]
🧰 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}
]
🔽 Sort by age:
sorted_users = sorted(users, key=lambda x: x['age'])
🔼 Sort by name (descending):
sorted_users = sorted(users, key=lambda x: x['name'], reverse=True)
🧠 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}
🔤 Sort by key:
sorted_by_key = dict(sorted(scores.items()))
# {'Alice': 82, 'Bob': 91, 'Charlie': 78}
🔢 Sort by value:
sorted_by_value = dict(sorted(scores.items(), key=lambda item: item[1]))
# {'Charlie': 78, 'Alice': 82, 'Bob': 91}
🔄 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]
With custom key:
words.sort(key=lambda x: len(x))
⚠️ .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'))
Works well when sorting by multiple keys too:
sorted_users = sorted(users, key=itemgetter('age', 'name'))
✨ 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)