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

Alex Gonzalez
  • 981
  • 1
  • 11
  • 17
  • Printing a dictionary uses `repr` instead of just printing the raw contents of the strings. – Ry- Mar 11 '13 at 23:37

1 Answers1

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.

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
  • 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: http://stackoverflow.com/questions/4184108/python-json-dumps-cant-handle-utf-8 – Alex Gonzalez Mar 11 '13 at 23:57
  • 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. – Pavel Anossov Mar 12 '13 at 00:01
  • 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. – Alex Gonzalez Mar 12 '13 at 00:11