Created
June 26, 2009 10:14
-
-
Save veryhappythings/136400 to your computer and use it in GitHub Desktop.
An example of sorting dicts of dicts for my blog
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
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