[英]Python Writing a Dictionary to Text File isn't producing correct output
I have a dictionary as such - 我有这样的字典-
d = {"Dave":("Male", "96"), "Alice":("Female", "98")}
I want to write it to a text file in such a format - 我想以这种格式将其写入文本文件-
Dave
Male
96
Alice
Female
98
This is my current code - 这是我当前的代码-
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))
It is, however, producing the following output in the text file: 但是,它将在文本文件中产生以下输出:
Dave
('Male', '96')
Alice
('Female', '98')
How can I adjust this? 我该如何调整? Please help! 请帮忙! Thanks. 谢谢。
When you convert a tuple
to a str
using formatting, you get the representation of the tuple, which is (roughly, there are 2 methods __str__
and __repr__
actually) what python prints when you print
the item in the console. 当您使用格式将tuple
转换为str
时,将获得tuple
的表示形式 ,(实际上,实际上有2种方法__str__
和__repr__
)在控制台中print
项目时python打印的内容。
To get elements without the tuple decorations, you have to unpack the tuple. 要获取没有元组装饰的元素,必须拆开元组的包装。 One option (using format
): 一种选择(使用format
):
for key, value in d.items():
f.write("{}\n{}\n{}\n".format(key,*value))
*
unpacks the elements of value
into 2 elements. *
将value
要素分解为2个要素。 format
does the rest 其余的format
An even more compact way would be to multiply the format string by 3 (less copy/paste) 一种更紧凑的方法是将格式字符串乘以3(减少复制/粘贴)
for key, value in d.items():
f.write(("{}\n"*3).format(key,*value))
I used the i in range
method that iterates for every value in every key - 我使用了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]))
The following works in Python 3.6: 以下在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')
You can unpack the tuple at the top of the for
loop. 您可以在for
循环的顶部解压缩元组。 Additionally, in Python 3.6, you can use the f-string mechanism to directly interpolate variable values into strings. 此外,在Python 3.6中,您可以使用f字符串机制将变量值直接插值到字符串中。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.