Sort a Dictionary

Andrew Dalke adalke at mindspring.com
Fri Aug 22 23:28:43 EDT 2003


Afanasiy:
> Why wouldn't [ksort] be a standard function?

Because it isn't needed all that often and can be built (when needed)
from the underlying primitives very simply.  Because if there are a
lot of similar methods then it becomes harder to remember what each
one does.

The normal practice is

keys = d.keys()
keys.sort()
for k in keys:
    ....

which isn't all that onerous.

> How about this one?
>
> http://www.php.net/manual/en/function.asort.php

The normal idiom for sorting by value then printing
the key/value pairs is

rev_items = [(v, k) for k, v in d.items()]
rev_items.sort()
for v, k in rev_items:
    print k, v

If you want that as a function return just the keys
in value order

def asort(d):
    rev_items = [(v, k) for k, v in d.items()]
    rev_items.sort()
    return [k for (v, k) in rev_items]

 As you can see, there are many ways you might want
to sort a dict.  Why should all of them be present in
the standard dict type when it's really a matter of two
extra lines to get what you need.  Seeing the code in
this case is much easier than memorizing the 7 different
sort functions mentioned in the PHP docs.

Additionally, Python's keys can be more complex than
a string or int.  Eg,

d = {}
d[ (0,0) ] = "home"
d[ (1,3) ] = "school"
d[ (4,2) ] = "work"

y_items = [(y, name) for ((x, y), name) in d.items()]
y_items.sort()
for y, name in y_items:
  print y, name

sorts by y position, ignoring x position.  PHP doesn't
have a function for that, but it follows pretty naturally
from the idiomatically Python way to do it.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list