Return 将函数内的多值字典转换为漂亮的格式

Return a multiple value dictionary within a function into a pretty format

所以我采取的前两个步骤如下:

  1. 我打开了一个文本文件。打印方法为我提供了这个:

    ["string1","a","b","c"] 
    ["string2","d","e","f"]
    ["string3","g","h","i"] 
    ["string4","j","k","l"]
    
  2. 我将这些列表转换成字典。现在看起来像这样:

    dictionary = {"string1":["a","b","c"], "string2":["d","e","f"],
                  "string3":["g","h","i"], "string4":["j","k","l"]}  
    

我的目标是 return 这个字典在一个函数中,所以当它在主函数中打印时看起来像这样:

{
"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() function。对于字符串,这些字符串尽可能有用,因为它们显示为 字符串文字 ,可以简单地复制和粘贴以重新创建它们的值。这意味着它们还会显示不可打印的字符或具有特殊含义的字符,如 转义序列。你的换行符就是这样的字符。

换句话说,您不能仅通过在字符串值中插入 \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']}

您可以使用模板字符串或多个打印调用来实现此目的。

虽然给出了一个很好的答案,这将是打印字典的另一种方法,通过将其 key/item 对转换为列表,结果相同,代码行数更少,此答案给出为备选方案:

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]))

但最后一行看起来更复杂,更少"readable",输出相同:

{
"string1":['a', 'b', 'c'],
"string2":['d', 'e', 'f'],
"string3":['g', 'h', 'i'],
"string4":['j', 'k', 'l']}