我正在做一项学校作业,要求我:
我有一些问题
write2file函数工作正常,可以使用字典创建文本文件。但是,当要把它拉回来并反转数据时,我得到一个类型错误,抱怨字符串索引必须是整数。我迷路了。如有任何帮助,请谅解
我是python新手。请温柔一点:)提前谢谢你帮我理解我做错了什么
<pre><code>
import os
ChessPlayerProfile = {
"Matt": [("Rating: ", 2200), ("FIDE ID: 0147632DF"), ("Member Status: ", True)],
"Will": [("Rating: ", 2200), ("FIDE ID: 3650298MK"), ("Member Status: ", False)],
"Jithu": [("Rating: ", 1900), ("FIDE ID: 5957200LH"), ("Member Status: ", True)],
"Lisa": [("Rating: ", 2300), ("FIDE ID: 7719328CX"), ("Member Status: ", False)],
"Nelson": [("Rating: ", 2500), ("FIDE ID: 6499012XX"), ("Member Status: ", True)],
"Miles": [("Rating: ", 1600), ("FIDE ID: 4392251TJ"), ("Member Status: ", True)],
}
def write2file():
with open("chessdict.txt", "w") as f: # Open file using context manager for memory safety
f.write(str(ChessPlayerProfile)) # dumping dict to file
# (wanted to use pickle but we need strings per instructions)
def Read_Invert_Write():
with open("chessdict.txt", "r") as f: # Read File 1
TempContent = f.read() # assign to temp variable
invert(TempContent) # Invert contents of temp variable
with open("new_dict.txt", "w") as f: # create File 2
f.write(str(TempContent)) # and write new dict from variable contents
def invert(d): # Previous function for inverting the dict
inverse = dict()
for key in d: # Iterate through the list that is saved in dict
val = d[key]
for item in val: # Check if in the inverted dict the key exists
if item not in inverse:
inverse[item] = [key] # If not then create a new list
else:
inverse[item].append(key)
return inverse
def main():
write2file()
Read_Invert_Write()
main()
</pre></code>
输出:
Traceback (most recent call last):
File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 44, in
main()
File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 43, in main
Read_Invert_Write()
File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 15, in Read_Invert_Write
invert(TempContent)
File "/home/vigz/PycharmProjects/pythonProject/copytest.py", line 32, in invert
val = d[key]
TypeError: string indices must be integers
给定一个文件
f
,创建方式如下:f.read()
的结果是一个str
,而不是一个dict
。因此,当您调用invert(f.read())
时:本质上是在
f.read()
中的字符上迭代,并尝试获取f.read()[character]
(这不是一个有效的操作)。具体地说,如果chessdict.txt
的内容是:在
invert(f.read())
中的迭代:其执行方式如下:
如果
chessdict.txt
包含JSON编码的字符串,您可以尝试:如果可以将
f
的内容解组为JSON,则将返回一个dict
。此时,您不妨重写invert
,以便它在键和值上迭代:当需要将字典写入文件时,应避免
str(your_dictionary)
:如果要将其转换为JSON编码字符串,应编写:这将正确地将其打包为JSON格式(避免将转义字符串(如
{\"foo\": ...}
)写入文件时出现问题)相关问题 更多 >
编程相关推荐