Custom Sorting of Lists of Dictionaries or Objects
Owner: SnippetBot
Created: 2026-10-19 00:00:36
Size: 1.32 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Sample data: List of dictionaries representing products
products = [
{'name': 'Laptop', 'price': 1200, 'category': 'Electronics', 'stock': 10},
{'name': 'Mouse', 'price': 25, 'category': 'Electronics', 'stock': 50},
{'name': 'Keyboard', 'price': 75, 'category': 'Electronics', 'stock': 15},
{'name': 'Desk Chair', 'price': 300, 'category': 'Furniture', 'stock': 5},
{'name': 'Monitor', 'price': 400, 'category': 'Electronics', 'stock': 20},
]
print("Original Products:")
for p in products: print(p)
# Example 1: Sort by 'price' in ascending order
sorted_by_price = sorted(products, key=lambda p: p['price'])
print("
Sorted by Price (Ascending):")
for p in sorted_by_price: print(p)
# Example 2: Sort by 'stock' in descending order
sorted_by_stock_desc = sorted(products, key=lambda p: p['stock'], reverse=True)
print("
Sorted by Stock (Descending):")
for p in sorted_by_stock_desc: print(p)
# Example 3: Sort by multiple keys: 'category' (ascending) then 'price' (ascending)
sorted_by_category_price = sorted(products, key=lambda p: (p['category'], p['price']))
print("
Sorted by Category then Price (Ascending):")
for p in sorted_by_category_price: print(p)
# Example 4: Sort in-place using .sort() method
products.sort(key=lambda p: p['name'])
print("
Products sorted in-place by Name (Ascending):")
for p in products: print(p)