Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我们如何将Python字典转换为.txt文件(格式)?_Python_Python 3.x_List_Dictionary - Fatal编程技术网

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

我们如何将Python字典转换为.txt文件(格式)?,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,例如,如果我有一个python字典,它看起来像: {'John': ['boy, 'american'], 'Jane': ['girl', 'canadian']}. 我们如何将其存储在.txt文件中,如下所示: sample.txt John boy american Jane girl canadian 是的,我在网上找到的。希望能有帮助 只是一个建议,而不是粘贴图像链接(如果需要,没有人可以从中复制),您可以发布代码本身,这将有助于操作。这不会按照要求以新行格式存储dict,而是

例如,如果我有一个python字典,它看起来像:

{'John': ['boy, 'american'], 'Jane': ['girl', 'canadian']}. 
我们如何将其存储在.txt文件中,如下所示:

sample.txt

John
boy
american

Jane
girl
canadian

是的,我在网上找到的。希望能有帮助


只是一个建议,而不是粘贴图像链接(如果需要,没有人可以从中复制),您可以发布代码本身,这将有助于操作。这不会按照要求以新行格式存储dict,而是使用撇号和大括号保存。您尝试过什么#WriteMyCodeForMe
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")