Print dict in sorted order

Paul Rubin http
Sun Jan 29 15:28:52 EST 2006


"Kamilche" <klachemin at comcast.net> writes:

> 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 my version.  Obviously you could save a line or two here and
there, depending on your stylistic preference.

================================================================

from sets import Set
from cStringIO import StringIO

def DictToString(d, preferred_order = ['gid', 'type',
                                       'parent', 'name']):
    r = StringIO()
    def out(k, v):
        r.write('%s:%s,'% (repr(k), repr(v)))
    r.write('{')
    for k in preferred_order:
        if k in d:
            out(k, d[k])
    for k in sorted([k1 for k1 in d.keys() if k1 not in Set(preferred_order)]):
        out(k, d[k])
    r.write('}')
    return r.getvalue()



More information about the Python-list mailing list