How do I sort a dictionary by value?
Share
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
You must login to ask question.
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it’s an implementation detail.
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])} OUTPUT: {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}