Show pageOld revisionsBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Sort List Of Dictionaries By Value ====== **General Information** Sorting a list of dictionaries by a value in the dictionary. ---- ====== Usage ====== Example output <code bash> ./sort-list-of-dictionary-by-value.py -> Sorted by Last Name: [{'first_name': 'Boba', 'last_name': 'Fett', 'side': 'none'}, {'first_name': 'Yoda', 'last_name': 'GreenGuy', 'side': 'rebels'}, {'first_name': 'Darth', 'last_name': 'Vader', 'side': 'empire'}] -> Sorted by First Name: [{'first_name': 'Boba', 'last_name': 'Fett', 'side': 'none'}, {'first_name': 'Darth', 'last_name': 'Vader', 'side': 'empire'}, {'first_name': 'Yoda', 'last_name': 'GreenGuy', 'side': 'rebels'}] </code> ---- ====== The Code ====== <code python sort-list-of-dictionary-by-value.py> #!/usr/bin/env python # Import itemgetter to sort by dictionary key from operator import itemgetter user_list = [ {'first_name': 'Yoda', 'last_name': 'GreenGuy', 'side': 'rebels'}, {'first_name': 'Darth', 'last_name': 'Vader', 'side': 'empire'}, {'first_name': 'Boba', 'last_name': 'Fett', 'side': 'none'} ] sorted_last_name = sorted(user_list, key=itemgetter('last_name')) sorted_first_name = sorted(user_list, key=itemgetter('first_name')) print("-> Sorted by Last Name:") print(sorted_last_name) print("\n-> Sorted by First Name:") print(sorted_first_name) </code> ---- python_wiki/sort_list_of_dictionaries_by_value.txt Last modified: 2019/05/25 23:50(external edit)