I am still new to python and I am playing around with saving data to text files. My problem is that when I try to access a dictionary it comes up with this error TypeError: string indices must be integers
but I don't know how to convert them.
This is what's inside my file:
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}
This is my code:
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()
If there is a more efficient way of storing the data?
I'd suggest using JSON to write the data out to a text file https://docs.python.org/3/library/json.html
You can use the json.dumps method to create JSON data that can be written to a file and use the json.loads method to convert the text from the file back in to a dictionary
Well since your question asks for "a more efficient way of storing the data" I'm going to say yes!
https://docs.python.org/3/library/shelve.html
Shelve is a great tool to store dictionaries persistently and change / edit the dictionary whenever. I'm currently using it for a discord bot project I'm working on and so far it's been great.
Here is some usage tips to get your started (pulled directly from the page I linked).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.