我还是 Python 新手,我正在尝试将数据保存到文本文件。我的问题是,当我尝试访问字典时会出现此错误,TypeError: string indices must be integers但我不知道如何转换它们。
这是我的文件中的内容:
Student 1/:{ "Topic 1" : 0,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 4}
Student 2/:{ "Topic 1" : 1,"Topic 2" : 2,"Topic 3" : 0,"Topic 4" : 0}
Student 3/:{ "Topic 1" : 1,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 1}
这是我的代码:
import ast #I thought this would fix the problem
def main():
data = {}
with open("test.txt") as f:
for line in f:
content = line.rstrip('\n').split('/:')
data[content[0]] = ast.literal_eval(content[1])
f.close()
print(data["Student 1"["Topic 1"]]) # works if I only do data[Student 1]
main()
如果有更有效的数据存储方式?
相关分类