YouTip LogoYouTip

Python Sort Dictionaries By Key Or Value

## How to Sort Dictionaries by Key or Value in Python In Python, dictionaries (`dict`) are collections of key-value pairs. While standard Python dictionaries (from Python 3.7+) maintain their insertion order, you often need to sort them by their keys or values for data analysis, reporting, or presentation. This tutorial covers how to sort dictionaries by key, by value, and how to sort complex structures like lists of dictionaries using Python's built-in functions. --- ## Understanding the `sorted()` Function The primary tool for sorting in Python is the built-in `sorted()` function. It returns a new sorted list from the items of any iterable. ### Syntax ```python sorted(iterable, key=None, reverse=False) ``` * **`iterable`**: The sequence (list, tuple, dictionary, etc.) to be sorted. * **`key`**: A function that serves as a key for the sort comparison (e.g., `lambda` functions or `operator.itemgetter`). * **`reverse`**: A boolean value. If set to `True`, the list elements are sorted in descending order. --- ## Example 1: Sorting a Dictionary by Key To sort a dictionary by its keys, you can pass the dictionary directly to the `sorted()` function. This returns a sorted list of the keys. You can then iterate over these keys to access their corresponding values. ```python def sort_by_key(): # Declare a dictionary key_value = {} # Initialize dictionary elements key_value = 56 key_value = 2 key_value = 12 key_value = 24 key_value = 18 key_value = 323 print("Sorting by Key:") # sorted(key_value) returns a sorted list of keys for key in sorted(key_value): print((key, key_value), end=" ") def main(): sort_by_key() if __name__ == "__main__": main() ``` ### Output ```text Sorting by Key: (1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18) ``` --- ## Example 2: Sorting a Dictionary by Value To sort a dictionary by its values, you can use the `key_value.items()` method, which returns a view of the dictionary's `(key, value)` tuple pairs. By passing a custom `lambda` function to the `key` parameter of `sorted()`, you can instruct Python to sort based on the values (the second element of each tuple, index `1`). ```python def sort_by_value(): # Declare a dictionary key_value = {} # Initialize dictionary elements key_value = 56 key_value = 2 key_value = 12 key_value = 24 key_value = 18 key_value = 323 print("Sorting by Value:") # Sort by value (kv), and use key (kv) as a tie-breaker sorted_tuples = sorted(key_value.items(), key=lambda kv: (kv, kv)) print(sorted_tuples) def main(): sort_by_value() if __name__ == "__main__": main() ``` ### Output ```text Sorting by Value: [(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)] ``` --- ## Example 3: Sorting a List of Dictionaries In real-world applications, you often work with a list of dictionaries (similar to JSON arrays). You can sort these lists based on specific dictionary keys. ```python # A list of dictionaries representing websites and their ages lis = [ {"name": "Taobao", "age": 100}, {"name": "Runoob", "age": 7}, {"name": "Google", "age": 100}, {"name": "Wiki", "age": 200} ] # 1. Sort by 'age' in ascending order print("Sorted by age (ascending):") print(sorted(lis, key=lambda i: i['age'])) print("\n") # 2. Sort by 'age' first, and then by 'name' (multi-level sorting) print("Sorted by age and then by name:") print(sorted(lis, key=lambda i: (i['age'], i['name']))) print("\n") # 3. Sort by 'age' in descending order print("Sorted by age (descending):") print(sorted(lis, key=lambda i: i['age'], reverse=True)) ``` ### Output ```text Sorted by age (ascending): [{'name': 'Runoob', 'age': 7}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Wiki', 'age': 200}] Sorted by age and then by name: [{'name': 'Runoob', 'age': 7}, {'name': 'Google', 'age': 100}, {'name': 'Taobao', 'age': 100}, {'name': 'Wiki', 'age': 200}] Sorted by age (descending): [{'name': 'Wiki', 'age': 200}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Runoob', 'age': 7}] ``` --- ## Key Considerations 1. **Return Type**: The `sorted()` function always returns a new **list** (either of keys, tuples, or dictionaries), leaving the original dictionary unmodified. 2. **Reconstructing a Dictionary**: If you need the final output to be a dictionary object instead of a list of tuples, you can cast the sorted result back into a dictionary using `dict()`: ```python sorted_dict = dict(sorted(key_value.items(), key=lambda item: item)) ``` 3. **Performance**: For large datasets, using `operator.itemgetter` can be faster than using `lambda` functions: ```python from operator import itemgetter # Sort by value sorted(key_value.items(), key=itemgetter(1)) ```
← Python Remove A Key From DictiPython String Reverse β†’