【发布时间】:2021-06-16 11:44:18
【问题描述】:
我正在做一项学校作业,要求我:
- 将我之前创建的字典作为字符串写入文件。
- 然后将该字典再次导入 python 并反转它
- 将倒排字典写入新文件。
我遇到了一些问题...
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
【问题讨论】:
标签: python file dictionary