[英]How do we convert a Python dictionary to a .txt file (with a format)?
For an example, if i have a dictionary in python that looks like:例如,如果我在 python 中有一个字典,看起来像:
{'John': ['boy, 'american'], 'Jane': ['girl', 'canadian']}.
how do we store it in.txt file as follows:我们如何将其存储在 .txt 文件中,如下所示:
sample.txt样本.txt
John
boy
american
Jane
girl
canadian
d = {'John': ['boy', 'american'], 'Jane': ['girl', 'canadian']}
with open('sample.txt', 'w') as f:
for k, v in d.items():
# write name
f.write("{}\n".format(k))
# write attributes of name
for elem in v:
f.write("{}\n".format(elem))
# write new line
f.write("\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.