Skip to content

Instantly share code, notes, and snippets.

@nara-l
Created May 24, 2018 12:32
Show Gist options
  • Save nara-l/cb465e24ab125752245c01d1dc1c7c09 to your computer and use it in GitHub Desktop.
Save nara-l/cb465e24ab125752245c01d1dc1c7c09 to your computer and use it in GitHub Desktop.
Sorting a dictionary by value
# Given a dictionary
>>> ds = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
>>> sorted(ds.items(), key=lambda y:y[1]) ## sorts values in ascending order
'''Result'''
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
# Or we can use itemgetter to sort by any item
from operator import itemgetter
>>> sorted(ds.items(), key=itemgetter(1)) ## sorts values in ascending order yields same result as above
'''Result'''
[('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