Tuesday, May 19, 2020

How to sort a list of dictionaries in python


# This is a list of dictionaries in python
list_of_dictionaries = [{'id':2, "name":"python"}, {'id':1, "name":"import"}]

# This is the list, sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'])

# This is the list, reverse sorted by the key "name"
sortedlist = sorted(list_of_dictionaries, key=lambda k: k['name'], reverse=True)

#shortcut to learn more about the sorted function
# https://docs.python.org/3/howto/sorting.html

#understanding what lambda means
# https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions



No comments:

Post a Comment