Sort Python Dictionaries by Key or Value

Posted by: scoopseven 13 years, 1 month ago

Dictionaries have no __order__ so when you're need to sort one, you're out of luck, right? Not so! Found this goodness with instructions on sorting/ordering Python dictionaries by key or value. I needed to sort a dictionary of regions alphabetically to populate a ChoiceField/select/dropdown box.
from operator import itemgetter regions = sorted(region_dict.iteritems(), key=itemgetter(1))
Before sort:
{3: 'West', 4: 'East', 5: 'South', 6: 'Mid-West'}
After sort:
[(4, 'East'), (6, 'Mid-West'), (5, 'South'), (3, 'West')]

Currently unrated


Recent Tweets

Recent Posts

Archive

2013
2012
2011
2010
2009
2008
2007
2006

Categories

Authors

Feeds

RSS / Atom