16

I'm currently testing a webservice that returns large amounts of JSON data in the form of dictionaries. The keys and values for those dictionaries are all unicode strings, and thus they print like

{u'key1':u'value', u'key2':u'value2'}

when printed to the screen in the interactive interpreter.

Now imagine that this is a 3-level deep, 40-element dictionary. All those u characters clutter up the display, making it hard to figure out, at a glance, what the real data actually is. Even when using pprint.

Is there any way to tell the interpreter that I don't care about the difference between normal strings and unicode strings? I don't need or want the u.

The only thing I've found that might have helped was the PYTHONIOENCODING environment variable. Unfortunately, setting it to 'ascii' or 'latin-1' doesn't make those u's go away.

I'm using Python 2.6, and I use either the regular python interpreter, or iPython.

coredumperror
  • 8,471
  • 6
  • 33
  • 42

2 Answers2

19

if it's json you want, just print json:

>>> import json
>>> print json.dumps({u'key1':u'value', u'key2':u'value2'}, indent=4)
{
    "key2": "value2", 
    "key1": "value"
}
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • Hmmm, that could work. Once I get back to the office I'll try that out. Thanks for the tip. – coredumperror Jun 26 '11 at 05:52
  • Ok, after trying this out, it's perfect! It's basically Santiago's idea from the other answer, with json.dumps() being the "function to print the dictionary". – coredumperror Jun 27 '11 at 18:48
0

Why don't you create your own function to print the dictionary? Python's default format is OK for fast, easy debugging, but absolutely inapproapiate for a 3-level deep, 40-element dictionary.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • Hmm, that could work, but it'd be more effort than this problem is really worth. I was hoping for something like a command-line switch to the interpreter. I'm already using pprint, which does all the formatting work to make these deep dictionaries somewhat readable, and I'd rather not re-invent the wheel. – coredumperror Jun 24 '11 at 22:58
  • well, you could wrap your strings and override their `repr` method. – salezica Jun 24 '11 at 23:10