[英]Return a multiple value dictionary within a function into a pretty format
因此,我现在采取的前两个步骤如下:
我打开了一个文本文件。 打印方法为我提供了这一点:
["string1","a","b","c"] ["string2","d","e","f"] ["string3","g","h","i"] ["string4","j","k","l"]
我将这些列表转换成字典。 现在看起来像这样:
dictionary = {"string1":["a","b","c"], "string2":["d","e","f"], "string3":["g","h","i"], "string4":["j","k","l"]}
我的目标是在函数中返回此字典,以便在主函数中打印时看起来像这样:
{
"string1":["a","b","c"],
"string2":["d","e","f"],
"string3":["g","h","i"],
"string4":["j","k","l"]}
我尝试在每个键之前应用换行符,但仅打印以下内容:
{"\nstring1":["a","b","c"], "\nstring2":["d","e","f"],"\nstring3":["g","h","i"],
"\nstring4":["j","k","l"]}
这是我的功能(包括主要功能):
import csv
def read_dictionary():
with open("text.tsv") as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter = "\t")
d = {}
for line in tsvreader:
first_row = line[0:1]
rest_rows = line[1:]
for strings in first_row: #converting lists into strings
d["\n"+strings] = rest_rows
return d
if __name__=="__main__":
print(read_dictionary())
字典(像所有内置容器一样)以其内容显示为表示形式,本质上在每个字典上使用repr()
函数 。 对于字符串,它们被认为是尽可能有用的,因为它们显示为字符串文字 ,可以直接将其复制并粘贴以重新创建其值。 这意味着它们还会显示不可打印的字符或具有特殊含义的字符作为转义序列 。 您的换行符就是这样的字符。
换句话说,仅在字符串值中插入\\n
字符就不能做您想做的事情。
相反,如果您确实想以这种方式显示字典,则需要进行自己的格式化。 只需自己打印出键和值即可:
def represent_dict(d):
print('{', end='') # no newline
first = True
for key, value in d.items():
# newline at the start, not end, with commas
print('{}\n{!r}: {!r}'.format('' if first else ',', key, value), end='')
first = False
print('}') # closing with a brace and a newline
删除阅读代码中的\\n
附加内容; 可以简化为仅使用字典理解直接生成字典:
def read_dictionary():
with open("text.tsv") as tsvfile:
tsvreader = csv.reader(tsvfile, delimiter = "\t")
return {row[0]: row[1:] for row in tsvreader}
represent_dict(read_dictionary())
通常,您应该将表示和数据结构分开。 键中的那些换行符很容易在其他地方引起问题,并且仅在这些位置用于演示输出。
输出演示:
>>> dictionary = {"string1":["a","b","c"], "string2":["d","e","f"],
... "string3":["g","h","i"], "string4":["j","k","l"]}
>>> represent_dict(dictionary)
{
'string1': ['a', 'b', 'c'],
'string2': ['d', 'e', 'f'],
'string3': ['g', 'h', 'i'],
'string4': ['j', 'k', 'l']}
虽然给出了很好的答案,但这将是打印字典的另一种方法,方法是将其键/项对转换为列表,结果相同,只需更少的代码行,此答案可以替代:
def print_mydict(my_dict):
my_list = list(my_dict.items())
print('{')
for i in my_list[:-1]:
print('"{}":{},'.format(i[0], i[1]))
print('"{}":{}}}'.format(my_list[-1][0], my_list[-1][1]))
但最后一行看起来更复杂且“可读性”更低,输出相同:
{
"string1":['a', 'b', 'c'],
"string2":['d', 'e', 'f'],
"string3":['g', 'h', 'i'],
"string4":['j', 'k', 'l']}
您可以使用模板字符串或多个打印调用来实现此目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.