打印字典,STR在Python
我对蟒蛇以下字典:打印字典,STR在Python
dic = {1:'Ááa',2:'lol'}
,如果我打印出现
print dic
{1: '\xc3\x81\xc3\xa1a', 2: 'lol'}
我怎样才能获得以下输出中?
print dic
{1: 'Ááa', 2: 'lol'}
不能做,因为数据结构内的字符串等的字典或列表由串不__str__
的__repr__
方法印刷。更多信息读What is the difference between str and repr in Python
返回包含对象的可打印表示的字符串。
作为替代方案,你可以将项目转换为字符串,并打印出来:
>>> print '{'+','.join([':'.join(map(str,k)) for k in dic.items()])+'}'
{1:Ááa,2:lol}
如果你不介意只是字符串,没有封闭的报价,你可以遍历dict
和自己打印每个键值对。
from __future__ import print_function
for key, value in dict_.iteritems():
print(key, value, sep=': ', end=',\n')
如果你打算打印一次,我会这样做,而不是建立一个字符串。如果您想要做其他事情,或者多次打印它们,请使用Kasra's answer。
但这会造成混淆,如果键或值有冒号,逗号,或者在他们换行符,输出将不会是一个有效的Python文字,但它的短升级到Python 3
我不确定这是做你想做的最好的方法。我创建了一个类来以您想要的方式表示数据。但是,您应该注意到字典数据类型不再被返回。这只是表示数据的一种快速方式。第一行# -*- coding: utf-8 -*-
全局指定编码类型。所以,如果你只是想打印你的字典,这将工作。
# -*- coding: utf-8 -*-
class print_dict(object):
def __init__(self, dictionary):
self.mydict = dictionary
def __str__(self):
represented_dict = []
for k, v in self.mydict.items():
represented_dict.append("{0}: {1}".format(k, v))
return "{" + ", ".join(represented_dict) + "}"
dic = {1: 'Ááa', 2: 'lol'}
print print_dict(dic)
与[Kasara的回答](https://stackoverflow.com/a/29590993/1561811)一样,考虑使用生成器表达式,而不是构建列表并将其传递给'str.join()'。 –
这是一个很好的添加修改。当我有机会重新实现时。 – reticentroot
或者可能不是。 [Padraic已经向我指出](https://stackoverflow.com/questions/29590948/printing-a-dictionary-with-str-in-python/29591238#comment47329651_29590993)that [str'join()'a listcomp实际上更高效](http://stackoverflow.com/a/9061024/2141635)。在我的系统中,我也得到了与Python 3类似的结果。 –
这工作在Python 3
罚款这是它的外观时,在Python Shell执行等。
>>> dic={1: 'Ááa',2: 'lol'}
>>> print(dic)
{1: 'Ááa', 2: 'lol'}
适用于Python3!升级时间 –
适用于我的Python-2.7。此外,地球上来自“霍拉”的地方。 – miradulo
“hola”怎么变成“lol”? –