Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python cheatsheet

How to sort dict...

By value

Return as a list of tuples:

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
#=> [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]

Return as an ordered dict:

from collections import OrderedDict

sorted_dict = OrderedDict(sorted_x)
#=> OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.