To sort a list of dictionaries in Python, you can use the sorted
function along with a lambda function as the key parameter. The lambda function takes each dictionary as an input and returns the value to be used for sorting.
Here's an example:
main.py218 chars8 lines
Output:
main.py89 chars4 lines
In the example above, we have a list of dictionaries list_of_dicts
with keys 'name' and 'age'. We then sort the list based on the value of 'age' using the lambda function lambda x: x['age']
, which takes each dictionary x
and returns its 'age' value. The sorted list is then stored in a new variable called sorted_list
.
Note that the sorted
function returns a new sorted list and does not modify the original list.
gistlibby LogSnag