Python将字典写入文本文件并不能产生正确的输出

时间:2017-02-18 20:13:16

标签: python dictionary text-files

我有一本字典 -

$ cat infile string 2 2 3 3 1 4 other 5 1 20 9 3 7 $ ./sorttuples infile string 1 4 2 2 3 3 other 3 7 5 1 20 9

我想以这种格式将其写入文本文件 -

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}

这是我目前的代码 -

Dave
Male
96
Alice
Female
98

然而,它在文本文件中产生以下输出:

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}

with open("dictionary.txt", 'w') as f:
    for key, value in d.items():
    f.write('%s \n %s \n' % (key, value))

我该怎么调整呢? 请帮忙!感谢。

4 个答案:

答案 0 :(得分:2)

使用格式转换 public static void scanner() { System.out.println("Is this a real scenario? Please enter 'Yes' or 'No'."); Scanner scan = new Scanner(System.in); String answer; answer = scan.nextLine(); //for (int x = 0; x < 2; x++ ) { if (answer.equals("Yes") || answer.equals("yes")) { real(); } else if (answer.equals("No") || answer.equals("no")) { hypothetical(); } else { System.out.println("Please enter 'Yes' or 'No'."); answer = scan.nextLine(); } } } tuple时,您会获得元组的表示,这是(大致有​​2种方法{{1}实际上当你str控制台中的项目时,python会打印什么。

要获取没有元组装饰的元素,您必须解压缩元组。一个选项(使用__str__):

__repr__

printformat的元素解包为2个元素。剩下的就是for key, value in d.items(): f.write("{}\n{}\n{}\n".format(key,*value))

更紧凑的方法是将格式字符串乘以3(减少复制/粘贴)

*

答案 1 :(得分:1)

我使用i in range方法迭代每个键中的每个值 -

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}

with open("dictionary.txt", 'w') as f:
    for key, value in d.items():
        for x in range(0,2):
            f.write('%s \n %s \n' % (key, value[x]))

答案 2 :(得分:1)

以下适用于Python 3.6:

d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
with open('dictionary.txt', mode='w') as f:
    for name, (sex, age) in d.items():
        f.write(f'{name}\n{sex}\n{age}\n')

您可以在for循环顶部解包元组。此外,在Python 3.6中,您可以使用f-string机制直接将变量值插入字符串。

答案 3 :(得分:0)

 d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
 with open("dictionary.txt", 'w') as f:
    for key in d.keys():
        f.write('%s \n' % (key))
        for v in d[key]:
           f.write('%s \n' % (v))