为了账号安全,请及时绑定邮箱和手机立即绑定

如何从此文本文件中读取字典?

如何从此文本文件中读取字典?

jeck猫 2021-06-07 16:21:26
我还是 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 problemdef 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()如果有更有效的数据存储方式?
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号