sort 2 separate dictionary by value python code example
Example 1: how to sort a dictionary by value in python
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
# Sort by key
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
Example 2: sorted python lambda
lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)
Example 3: python sort dict by value
A={1:2, -1:4, 4:-20}
{k:A[k] for k in sorted(A, key=A.get)}
output:
{4: -20, 1: 2, -1: 4}