簡體   English   中英

我們如何將 Python 字典轉換為 .txt 文件(帶有格式)?

[英]How do we convert a Python dictionary to a .txt file (with a format)?

例如,如果我在 python 中有一個字典,看起來像:

{'John': ['boy, 'american'], 'Jane': ['girl', 'canadian']}. 

我們如何將其存儲在 .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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM