order list of dictionaries in python

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.py
list_of_dicts = [{'name': 'John', 'age': 28},
                 {'name': 'Mary', 'age': 25},
                 {'name': 'Bob', 'age': 32}]

sorted_list = sorted(list_of_dicts, key=lambda x: x['age'])

print(sorted_list)
218 chars
8 lines

Output:

main.py
[{'name': 'Mary', 'age': 25},
 {'name': 'John', 'age': 28},
 {'name': 'Bob', 'age': 32}]
89 chars
4 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