python_wiki:sort_list_of_dictionaries_by_value

Sort List Of Dictionaries By Value

General Information

Sorting a list of dictionaries by a value in the dictionary.


Usage

Example output

./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'}]

The Code

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)

  • python_wiki/sort_list_of_dictionaries_by_value.txt
  • Last modified: 2019/05/25 23:50
  • (external edit)