Differences
This shows you the differences between two versions of the page.
— |
python_wiki:sort_list_of_dictionaries_by_value [2019/05/25 23: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> | ||
+ | ./ | ||
+ | |||
+ | -> Sorted by Last Name: | ||
+ | [{' | ||
+ | |||
+ | -> Sorted by First Name: | ||
+ | [{' | ||
+ | </ | ||
+ | |||
+ | ---- | ||
+ | |||
+ | ====== The Code ====== | ||
+ | |||
+ | <code python sort-list-of-dictionary-by-value.py> | ||
+ | # | ||
+ | |||
+ | # Import itemgetter to sort by dictionary key | ||
+ | from operator import itemgetter | ||
+ | |||
+ | user_list = [ {' | ||
+ | |||
+ | sorted_last_name = sorted(user_list, | ||
+ | sorted_first_name = sorted(user_list, | ||
+ | |||
+ | print(" | ||
+ | print(sorted_last_name) | ||
+ | |||
+ | print(" | ||
+ | print(sorted_first_name) | ||
+ | </ | ||
+ | |||
+ | ---- | ||