Skip to content

Instantly share code, notes, and snippets.

@jinyangustc
Last active December 5, 2019 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jinyangustc/8a0434881daf708a58d9a9a805263a4e to your computer and use it in GitHub Desktop.
Save jinyangustc/8a0434881daf708a58d9a9a805263a4e to your computer and use it in GitHub Desktop.
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