Skip to content

Instantly share code, notes, and snippets.

@johnpena
Created February 8, 2011 20:05
Show Gist options
  • Save johnpena/817103 to your computer and use it in GitHub Desktop.
Save johnpena/817103 to your computer and use it in GitHub Desktop.
Strategies for sorting dictionaries in python
import operator
def sort_dict(d):
"""
Sorts a dict by it's values, assuming the values are ints.
"""
return sorted(d.iteritems(), key=lambda (k,v): (v,k), reverse=True)
def sort_dict_list(l, key):
"""
Sorts a list of dicts by the value of each key.
"""
return sorted(l, key=operator.itemgetter(key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment