Python 如何从这个文本文件中读取词典?

Python 如何从这个文本文件中读取词典?,python,python-3.x,Python,Python 3.x,我对python还是新手,我正在尝试将数据保存到文本文件中。我的问题是,当我试图访问字典时,它会出现以下错误TypeError:string索引必须是整数,但我不知道如何转换它们 这是我的文件中的内容: Student 1/:{“主题1:0”,主题2:0,主题3:0,主题4:4} 学生2/:{“专题1”:1,“专题2”:2,“专题3”:0,“专题4”:0} 学生3/:{“专题1”:1,“专题2”:0,“专题3”:0,“专题4”:1} 这是我的代码: import ast #I thought

我对python还是新手,我正在尝试将数据保存到文本文件中。我的问题是,当我试图访问字典时,它会出现以下错误
TypeError:string索引必须是整数,但我不知道如何转换它们

这是我的文件中的内容:

Student 1/:{“主题1:0”,主题2:0,主题3:0,主题4:4}
学生2/:{“专题1”:1,“专题2”:2,“专题3”:0,“专题4”:0}
学生3/:{“专题1”:1,“专题2”:0,“专题3”:0,“专题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()

如果有更有效的方法存储数据?

我建议使用JSON将数据写入文本文件


您可以使用json.dumps方法创建可以写入文件的json数据,并使用json.loads方法将文件中的文本转换回字典,因为您的问题要求“一种更有效的存储数据的方法”,我会说是的

Shelve是一个很好的工具,可以持久地存储词典,并随时更改/编辑词典。我目前正在为一个discord机器人项目使用它,到目前为止,它非常棒

以下是一些使用技巧,可以帮助您开始使用(直接从我链接的页面中获取)


您希望表达式
“Student 1”[“Topic 1”]
的值是多少<代码>“学生1”
没有索引
“主题1”
,因此…?更改为
数据[“学生1”][“主题1”]
。不确切地知道您想知道什么,但您可以通过使用
打印(数据[“学生1”][“主题1”])轻松地消除
类型错误
而不是你的问题。哎呀,那是个愚蠢的错误,谢谢杜明和马蒂诺
import shelve

d = shelve.open(filename)  # open -- file may get suffix added by low-level
                           # library

d[key] = data              # store data at key (overwrites old data if
                           # using an existing key)
data = d[key]              # retrieve a COPY of data at key (raise KeyError
                           # if no such key)
del d[key]                 # delete data stored at key (raises KeyError
                           # if no such key)

flag = key in d            # true if the key exists
klist = list(d.keys())     # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]        # this works as expected, but...
d['xx'].append(3)          # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']             # extracts the copy
temp.append(5)             # mutates the copy
d['xx'] = temp             # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()                  # close it