Skip to content

Instantly share code, notes, and snippets.

@ferminhg
Created May 9, 2019 15:24
Show Gist options
  • Select an option

  • Save ferminhg/3c8787870cca64fbda40a5b1e6db2b6d to your computer and use it in GitHub Desktop.

Select an option

Save ferminhg/3c8787870cca64fbda40a5b1e6db2b6d to your computer and use it in GitHub Desktop.
Sort dict by value
# How to sort a Python dict by value
# (== get a representation sorted by value)
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# Or:
>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment