Answers for "how to order dict by value in python"

5

python sort a dictionary by values

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

sort_by_key = dict(sorted(x.items(),key=lambda item:item[0]))
sort_by_value = dict(sorted(x.items(), key=lambda item: item[1]))

print("sort_by_key:", sort_by_key)
print("sort_by_value:", sort_by_value)

# sort_by_key: {0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
# sort_by_value: {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Posted by: Guest on July-12-2021
0

sort dictionary by values

from collections import OrderedDict
dd = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print(dd)
Posted by: Guest on November-17-2020

Code answers related to "how to order dict by value in python"

Python Answers by Framework

Browse Popular Code Answers by Language