Skip to content

Instantly share code, notes, and snippets.

@randomslices
Created July 21, 2016 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randomslices/c804136465d4954a17db94ddde714704 to your computer and use it in GitHub Desktop.
Save randomslices/c804136465d4954a17db94ddde714704 to your computer and use it in GitHub Desktop.
Sort dict, n largest
# 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