[英]How to convert a txt file with dictionary format to dataframe in python?
[英]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.