sort a list of dictionaries by value code example
Example 1: sort list of dictionaries python
unsorted_list = [{"key1":5, "key2":2}, {"key1":5, "key2":1}]
sorted_list = sorted(unsorted_list, key=lambda k: k["key2"])
Example 2: python - sort dictionary by value
d = {'one':1,'three':3,'five':5,'two':2,'four':4}
# Sort
a = sorted(d.items(), key=lambda x: x[1])
# Reverse sort
r = sorted(d.items(), key=lambda x: x[1], reverse=True)
Example 3: sort dict by value
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Example 4: sort list of dictionaries python by value
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])