0

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
1
  • Printing a dictionary uses repr instead of just printing the raw contents of the strings. Commented Mar 11, 2013 at 23:37

1 Answer 1

6

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

3 Comments

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/…
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.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.