Sort Python Dictionaries by Key or Value

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')]


Next entry

Previous entry

Similar entries


Comments

Comments are closed.


Pingbacks

Pingbacks are open.


Trackbacks

Trackback URL