I have a file which is simple:
# -*- coding: utf-8 -*-
a = u'Alegría'
print a
print {'a': a}
The output is:
Alegría
{'a': u'Alegr\xeda'}
Why I am getting that instead of:
Alegría
{'a': u'Alegría'}
Thanks in advance
asked Mar 11, 2013 at 23:34
Alex Gonzalez
9912 gold badges11 silver badges17 bronze badges
1 Answer 1
dict's string representation calls repr on keys and values, and repr tries its best to make a string representation that you can paste in any file or interpreter, with or with an encoding declared, and get the object back.
Your string is fine, it's just a safe representation.
answered Mar 11, 2013 at 23:37
Pavel Anossov
63.4k16 gold badges156 silver badges125 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Alex Gonzalez
I was trying to print that to a file by serializing it to JSON. I guess JSON works in a similar way as repr, since I was getting the ugly {'a': u'Alegr\xeda'} printed to the file. Would you know how to serialize that to {'a': u'Alegría'}? Thanks Edit: I think I found the answer: stackoverflow.com/questions/4184108/…
Pavel Anossov
JSON shouldn't contain non-ASCII characters, and string representation of python dicts are not valid JSON. A JSON object with key
a and value Alegría would look like this: {"a": "Alegr\u00eda"}. Why does it matter to you what the serialized format looks like? You json.dump it on one end, json.load it on the other and get exactly what you dumped.Alex Gonzalez
I want to dump the dict to a file, then edit it by hand and finally load it with JavaScript. It would be nice to have it nicely printed in the JSON file so I can easily edit it since it is more readable.
lang-py
reprinstead of just printing the raw contents of the strings.