In Python, dictionaries are unordered collections of key-value pairs. Sometimes, we need to sort a dictionary either by its keys or by its values. This can be done easily using the built-in sorted() function.
|
1 2 3 4 5 6 7 8 9 10 |
# Example dictionary d = {'a': 3, 'c': 1, 'b': 2} # Sort dictionary items by value sorted_by_val = sorted(d.items(), key=lambda x: x[1]) print(sorted_by_val) # [('c', 1), ('b', 2), ('a', 3)] # Sort dictionary items by key sorted_by_key = sorted(d.items(), key=lambda x: x[0]) print(sorted_by_key) # [('a', 3), ('b', 2), ('c', 1)] |
Output:
|
1 2 |
[('c', 1), ('b', 2), ('a', 3)] [('a', 3), ('b', 2), ('c', 1)] |
Last Updated on 2025-08-24 by gantovnik
Recent Comments