Print dict in sorted order

Kamilche klachemin at comcast.net
Sun Jan 29 15:06:39 EST 2006


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!



def DictToString(d, preferred_order = ['gid', 'type',
                                       'parent', 'name']):
    ' Return a string containing the sorted dict'
    keys = d.keys()
    keys.sort()
    sortmax = len(preferred_order)
    for i in range(sortmax-1, -1, -1):
        sortkey = preferred_order[i]
        try:
            index = keys.index(sortkey)
        except ValueError:
            continue
        temp = keys[index]
        del keys[index]
        keys.insert(0, temp)
    s = []
    s.append('{')
    max = len(keys)
    for i in range(max):
        key = keys[i]
        val = d[key]
        s.append(repr(key))
        s.append(': ')
        s.append(repr(val))
        if i < max-1:
            s.append(', ')
    s.append('}')
    return ''.join(s)


def main():
    d = {'whatever': 145,
         'gid': 12345678901234567890,
         'name': 'Name',
         'type': 'an egg',
         32: 'Thirty-two (32)'}

    # Convert dicts to strings
    s1 = str(d)
    s2 = DictToString(d)
    print "Python str:", s1
    print "Custom str:", s2

    # Verify the strings are different
    assert(s1 != s2)

    # Convert the strings back to dicts
    d1 = eval(s1)
    d2 = eval(s2)

    # Verify the dicts are equivalent
    assert(d1 == d2)

    print "\nSuccess!\n"


    
main()




More information about the Python-list mailing list