Sort a Dictionary

Peter Otten __peter__ at web.de
Sat Aug 23 04:29:30 EDT 2003


Andrew Dalke wrote:

> def ksort(d, func = None):
>     keys = d.keys()
>     keys.sort(func)
>     return keys
> 
> for k in ksort(d):
>     print k, v
> 
> 
> And no, I haven't tested it.  ;)
> 

and no, it doesn't work. Try

for k in ksort(d):
    print k, d[k]

or go with

items = d.items()
items.sort()
for key, value in items:
    print key, "-->", value

I reckon that for me the extra function doesn' t pay off, but if you must,
use the generic

def sorted(seq, func=None):
    items = list(seq) # create a copy to omit side effects      
    items.sort(func)
    return items

for key, value in sorted(d.items()):
    print key, "-->", value

which would be useful for any iterable.

Peter





More information about the Python-list mailing list