how to sort a dictionary by value in python

43

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)

order dictionary by value python -

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_dict = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
print(sorted_dict)
#{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Comments

Submit
0 Comments