Ordering in the printout of a dictionary

Marc Christiansen usenetmail at solar-empire.de
Tue Mar 18 03:36:44 EDT 2014


Chris Angelico <rosuav at gmail.com> wrote:
> On Tue, Mar 18, 2014 at 11:32 AM, Mok-Kong Shen
> <mok-kong.shen at t-online.de> wrote:
>> Is there a way to force a certain ordering of the printout or else
>> somehow manage to get at least a certain stable ordering of the
>> printout (i.e. input and output are identical)?
> 
> Yes; instead of simply printing it out (which calls repr()),
> explicitly iterate over it, like this:
> 
> def display(d):
>    return '{'+','.join('%r: %r'%(key,d[key]) for key in sorted(d))+'}'
> 
[...]
> At least, it's consistent as long as the keys all sort consistently,
> which they will if you use simple strings. Other types of keys may not
> work, and in fact mixing types may cause an exception:
> 
>>>> print(display({True:1,"Hello":2}))
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "<stdin>", line 2, in display
> TypeError: unorderable types: str() < bool()
> 
> But for strings, this is the easiest way to get what you're looking for.

I would say using pprint.pprint is even easier and it works with your
failing example:

>>> pprint.pprint({True:1,"Hello":2})
{True: 1, 'Hello': 2}

Ciao
Marc



More information about the Python-list mailing list