Print dict in sorted order

Raymond Hettinger python at rcn.com
Mon Jan 30 02:55:23 CET 2006


> from itertools import count, izip
>
> def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']):
>     last = len(preferred_order)
>     rank = dict(izip(preferred_order, count()))
>     pairs = d.items()
>     pairs.sort(key=lambda (k,v): rank.get(k, (last, k, v)))
>     return '{%s}' % repr(pairs)[1:-1]

P.S. If you need the string to evaluatable like repr(d), then change
the last line to:

    return 'dict(%r)' % pairs




More information about the Python-list mailing list