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.

1

2 Answers 2

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"
}
2
  • Hmmm, that could work. Once I get back to the office I'll try that out. Thanks for the tip. Jun 26, 2011 at 5: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". Jun 27, 2011 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.

2
  • 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. Jun 24, 2011 at 22:58
  • well, you could wrap your strings and override their repr method.
    – salezica
    Jun 24, 2011 at 23:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.