简体   繁体   中英

Pythonic way to encode list items nested in dict

On Console:

>>> print {"key": ["äüö"]}
{'key': ['\xc3\xa4\xc3\xbc\xc3\xb6']}

How can I easily let python print something like this:

>>> print {"key": ["äüö"]}
{'key': ['äüö']}

I don't like to print unicode characters like in How to print Unicode character in Python? I like to have an easy way to print the content of a dictionary.

When you print a collection with Python 2, for instance a dict or a list , Python uses the repr() function to print the items of the collections.

In the case of a string (unicode string) you get escaped characters…

To do what you want, using Python 2, you need to print the dictionary yourself, like this:

>>> d = {"key": [u"äüö"]}
>>> for k, v in d.iteritems():
...     print(u"{k}: [{v}]".format(k=k, v=u", ".join(u"'{0}'".format(i) for i in v)))

You get:

key: ['äüö']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM