简体   繁体   English

python编码嵌套在dict中的列表项的方法

[英]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: 我如何轻松地让python打印如下内容:

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

I don't like to print unicode characters like in How to print Unicode character in Python? 我不喜欢像在Python中打印Unicode字符中那样打印unicode字符 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. 当您使用Python 2打印集合时,例如dictlist ,Python使用repr()函数来打印集合项。

In the case of a string (unicode string) you get escaped characters… 如果是字符串(unicode字符串),则会得到转义字符…

To do what you want, using Python 2, you need to print the dictionary yourself, like this: 要使用Python 2进行所需的操作,您需要自己打印字典,如下所示:

>>> 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: ['äüö']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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