【问题标题】:Pythonic way to encode list items nested in dictPythonic 编码嵌套在 dict 中的列表项的方法
【发布时间】:2018-06-02 23:23:56
【问题描述】:

在控制台上:

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

我怎样才能轻松地让 python 打印这样的东西:

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

我不喜欢像 How to print Unicode character in Python? 那样打印 unicode 字符我喜欢有一种简单的方法来打印字典的内容。

【问题讨论】:

  • 切换到python3
  • 你应该使用 unicode 字符串:u"äüö"(而不是字节字符串)。
  • @Mel:这并不是真正的重复。在这里,OP 想要打印字典的内容。为此,Python 使用了repr() 函数,所以他得到了转义字符。

标签: python list dictionary encoding


【解决方案1】:

当您使用 Python 2 打印集合时,例如 dictlist,Python 使用 repr() 函数来打印集合的项目。

如果是字符串(unicode 字符串),您会得到转义字符……

要使用 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)))

你得到:

key: ['äüö']

【讨论】:

  • 好的,很好的解决方案。但是,如果集合更复杂怎么办。例如,更多带有嵌套列表的嵌套字典?所以我必须写一个更复杂的解析器。
猜你喜欢
  • 2021-12-28
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 2019-01-25
  • 2012-11-18
  • 1970-01-01
  • 2013-03-24
相关资源
最近更新 更多