在Python中用str打印字典

2024-05-20 02:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下关于python的字典:

dic = {1:'Ááa',2:'lol'}

如果我打印出来

^{pr2}$

如何获得以下输出?在

print dic
{1: 'Ááa', 2: 'lol'}  

Tags: 字典printloldicpr2
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)

不能像dictionary或list这样的数据结构中的字符串那样由string not ^{}^{}方法打印。更多信息请阅读What is the difference between str and repr in Python

repr(object)

Return a string containing a printable representation of an object.

另一种方法是将项目转换为字符串并打印:

>>> 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文本,这确实会让人困惑,但这是升级到python3之外最简单的方法。在

相关问题 更多 >