Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.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 我想将元组作为键的字典转换为特定格式,然后将其存储在文件中_Python_Python 3.x - Fatal编程技术网

Python 我想将元组作为键的字典转换为特定格式,然后将其存储在文件中

Python 我想将元组作为键的字典转换为特定格式,然后将其存储在文件中,python,python-3.x,Python,Python 3.x,我有一本字典dic={1,2,3:3,2,3,4:2,3,4,8:5} 我希望它以指定格式保存在文本文件output.txt中 1 2 3 (3) 2 3 4 (2) 3 4 8 (5) 为此任务修改以下代码 dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5} with open('output.txt', 'w') as file: file.write(str(dic)) 迭代字典并将内容写入文本文件 例: 这里我们只需将键和值传递给fo

我有一本字典dic={1,2,3:3,2,3,4:2,3,4,8:5} 我希望它以指定格式保存在文本文件output.txt中

1 2 3 (3)
2 3 4 (2)
3 4 8 (5)
为此任务修改以下代码

dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}    
with open('output.txt', 'w') as file:
    file.write(str(dic))

迭代字典并将内容写入文本文件

例:

这里我们只需将键和值传递给format函数。我认为不需要对这件事做任何其他的操作


str.format是Python3中的字符串格式化方法之一,它允许多次替换和值格式化。此方法允许通过位置格式连接字符串中的元素。

好的,那么您在文件中看到的内容与希望在文件中看到的内容之间有什么区别?这能让你对下一步的改变有什么想法吗?当你手工写出你想要的输出时,你能用英语一步一步地描述你是如何计算的吗?file.write{}{}\n.format.joink,v write to file。TypeError:序列项0:应为str实例,int founduse.joinmapstr,k
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
    for k, v in dic.items():           #Iterate dic
        file.write("{} ({}) \n".format(" ".join(map(str, k)), v))  #write to file. 
dic = {(1,2,3): 3, (2,3,4): 2, (3,4,8): 5}
with open('output.txt', 'w') as file:
    for k, v in dic.items():           #Iterate dic
        file.write("{} ({}) \n".format(k, v))  #write to file.