how to pretty-print Python dict with unicode?

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Aug 4 19:24:29 EDT 2010


On Wed, Aug 4, 2010 at 3:15 PM, kj <no.email at please.post> wrote:
>
>
>
> Is there a simple way to get Python to pretty-print a dict whose
> values contain Unicode?  (Of course, the goal here is that these
> printed values are human-readable.)
>
> If I run the following simple script:
>
> from pprint import pprint
> x = u'\u6c17\u304c\u9055\u3046'
> print '{%s: %s}' % (u'x', x)
> print {u'x': x}
> pprint({u'x': x})
>
> The first print statement produces perfectly readable Japaneuse,
> but the remaining statements both produce the line
>
> {u'x': u'\u6c17\u304c\u9055\u3046'}
>
> I've tried everything I can think of (including a lot of crazy
> stuff) short of re-writing pprint from scratch (which I think would
> be faster than grokking it and hacking at it).
>
> Isn't there an easier way to do this?
>
> Thanks!
>
> ~K

use Python 3? http://www.python.org/dev/peps/pep-3138/

Or just iterate over the items and print them out yourself. The reason
you see the escaped values is that str(dict()) calls repr on all the
items. If you convert them to strings using str instead of repr(), it
will work the way you want.



More information about the Python-list mailing list