Sort List of Dictionaries by Value in Python
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This code demonstrates how to sort a list of dictionaries by a specific key using Python's built-in sort() method. The key parameter allows you to specify a function that returns the value to compare for each element.
The myFunc function returns the value of the 'year' key from each dictionary. When passed as the key, it sorts the list in ascending order based on the year.
To use this technique, define any function that extracts the desired sorting value, then pass it to sort(key=...). This is useful for sorting objects, dictionaries, or custom classes by an attribute.
- sort() modifies the list in place.
- For descending order, add
reverse=True. - Lambdas can also be used for simple key functions.