Created
July 21, 2016 13:48
-
-
Save randomslices/c804136465d4954a17db94ddde714704 to your computer and use it in GitHub Desktop.
Sort dict, n largest
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
# sort dictionary by value | |
>>> sorted(d.iteritems(), key=itemgetter(1), reverse=True) | |
[('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)] | |
# sort dict by keys: | |
>>> sorted(d, key=d.__getitem__, reverse=True) | |
['b', 'd', 'c', 'a', 'e'] | |
# Also, Python 2.5's heapq.nlargest() function addresses the common use | |
# case of finding only a few of the highest valued items: | |
>>> nlargest(2, d.iteritems(), itemgetter(1)) | |
[('b', 23), ('d', 17)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment