Print dict in sorted order

Michael Spencer mahs at telcopartners.com
Mon Jan 30 03:40:35 CET 2006


Raymond Hettinger wrote:
>> 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
> 
or:

def dict2str(d, preferred_order = ['gid', 'type', 'parent', 'name']):
     pairs = [(item, d[item]) for item in preferred_order]
     #preferred_order = set(preferred_order) # if preferred_order is big
     pairs.extend(sorted((k, v) for k,v in d.iteritems() if k not in 
preferred_order))
     return '{%s}' % repr(pairs)[1:-1]

Michael




More information about the Python-list mailing list