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" } 
Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm, that could work. Once I get back to the office I'll try that out. Thanks for the tip.
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".
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 Comments

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.
well, you could wrap your strings and override their repr method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.