Skip to content

Instantly share code, notes, and snippets.

@xiaom
Last active February 11, 2020 09:39
Show Gist options
  • Save xiaom/938400 to your computer and use it in GitHub Desktop.
Save xiaom/938400 to your computer and use it in GitHub Desktop.
sort dictionary by value
# http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value
# http://wiki.python.org/moin/HowTo/Sorting/
import operator
x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1),reverse=True)
y = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
# sort by age
sorted_y = sorted(y, key=lambda student: student[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment