Created
May 24, 2018 12:32
-
-
Save nara-l/cb465e24ab125752245c01d1dc1c7c09 to your computer and use it in GitHub Desktop.
Sorting a dictionary by value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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