Essentially, I want to print a dictionary such that it uses str()
instead of repr()
to stringify its keys and values.
This would be especially useful when saving a traceback string in some json. But this appears to be much more difficult than I would imagine:
In [1]: import pprint, json
In [2]: example = {'a\tb': '\nthis\tis\nsome\ttext\n'}
In [3]: print(example)
{'a\tb': '\nthis\tis\nsome\ttext\n'}
In [4]: str(example)
Out[4]: "{'a\\tb': '\\nthis\\tis\\nsome\\ttext\\n'}"
In [5]: pprint.pprint(example)
{'a\tb': '\nthis\tis\nsome\ttext\n'}
In [6]: pprint.pformat(example)
Out[6]: "{'a\\tb': '\\nthis\\tis\\nsome\\ttext\\n'}"
In [7]: json.dumps(example, indent=2)
Out[7]: '{\n "a\\tb": "\\nthis\\tis\\nsome\\ttext\\n"\n}'
In [8]: print(json.dumps(example, indent=2))
{
"a\tb": "\nthis\tis\nsome\ttext\n"
}
The behaviour I want (and expect) is this:
> print(d)
{'a b': '
this is
some text
'}
> pprint.pprint(d)
{
'a b': '
this is
some text
'
}
or maybe, if pprint were really smart:
> pprint.pprint(d)
{
'a b': '
this is
some text
'
}
...but I can't seem to built-in way to do this!
I'd like to know what the standard/best way to do this is, and if there isn't one, why not? Is there a special reason that repr()
is always called on strings instead of str()
when printing dicts (and other containers)?