Answers for "sort dictionary by its value in python"

35

how can I sort a dictionary in python according to its values?

s = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
k = dict(sorted(s.items(),key=lambda x:x[0],reverse = True))
print(k)
Posted by: Guest on November-23-2020
0

sort dict by value python 3

>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
...     k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)
Posted by: Guest on September-17-2020
0

python sort dictionary items by value

def sorted_dict_by_value(d: dict, reverse=False):
    # Sort the dictionary items by values
    marklist = sorted(d.items(), key=lambda x: x[1], reverse=reverse)
    return dict(marklist)
Posted by: Guest on September-01-2021

Code answers related to "sort dictionary by its value in python"

Python Answers by Framework

Browse Popular Code Answers by Language