[Tutor] Sorting the Dictionary Set?

Steven D'Aprano steve at pearwood.info
Tue Jul 6 16:58:52 CEST 2010


On Wed, 7 Jul 2010 12:38:55 am Ken G. wrote:
> Is there a way to sort a dictionary?

Not directly, dictionaries are unsorted and unsortable. They print in an 
arbitrary order.

If you need to operate on dictionaries in a specific, non-arbitrary 
order, you need to extract the keys, sort them, and then work from 
them. Example:

keys = mydict.keys()
keys.sort()
for key in keys:
    value = mydict[key]
    print "the value of key %s is %s" (key, value)

I'm sure you can adapt that example to what you're trying to do :)


-- 
Steven D'Aprano


More information about the Tutor mailing list