Print dict in sorted order
Raymond Hettinger
python at rcn.com
Sun Jan 29 20:39:39 EST 2006
[Kamilche]
> I have a code snippet here that prints a dict in an arbitrary order.
> (Certain keys first, with rest appearing in sorted order). I didn't
> want to subclass dict, that's error-prone, and overkill for my needs. I
> just need something that returns a value like dict.__str__, with a key
> ordering I specify.
>
> If you have any opinions on how it could be made better, I'm all ears!
Here's one more version to throw in the mix:
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]
d = dict(gid=10, type=20, parent=30, name=40, other=50, rest=60)
print dict2str(d)
Raymond
More information about the Python-list
mailing list