[[python_wiki:sort_list_of_dictionaries_by_value]]

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python_wiki:sort_list_of_dictionaries_by_value [2019/05/26 03:50] (current)
Line 1: Line 1:
 +====== 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/26 03:50
  • (external edit)