Skip to content

Instantly share code, notes, and snippets.

@veryhappythings
Created June 26, 2009 10:14
Show Gist options
  • Save veryhappythings/136400 to your computer and use it in GitHub Desktop.
Save veryhappythings/136400 to your computer and use it in GitHub Desktop.
An example of sorting dicts of dicts for my blog
from operator import itemgetter
files = {
'first' : {'filename': 'first.xml', 'priority': 0},
'second': {'filename': 'second.xml', 'priority': 4},
'third' : {'filename': 'third.xml', 'priority': 0},
'fourth': {'filename': 'fourth.xml', 'priority': 3},
'fifth' : {'filename': 'fifth.xml', 'priority': 6},
}
# Order isn't maintained in a dict
for name, item in files.iteritems():
print name, item
# If you don't need the key/value pairs to be maintained, itemgetter works just fine
for item in sorted(files.values(), key=itemgetter('priority')):
print item
# If you need those key/value pairs, you can use a lambda instead
for name, item in sorted(files.items(), key=lambda i: i[1]['priority']):
print name, item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment