简体   繁体   English

我们如何将 Python 字典转换为 .txt 文件(带有格式)?

[英]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")

Yeah I found this online.是的,我在网上找到了这个。 Hopefully it helps.希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM