Sort a Dictionary

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


Afanasiy:
> This is fairly simple in PHP, how do I do it in Python?
>
> http://www.php.net/manual/en/function.ksort.php

def ksort(d, func = None):
    keys = d.keys()
    keys.sort(func)
    return keys

for k in ksort(d):
    print k, v

As a bonus, you don't need to tell the sort to sort numerically
vs. lexigraphically --- Python's strong typing knows that by
default.  You can pass in an alternate compare function if you
want.

And no, I haven't tested it.  ;)

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list