There are similar questions/answers on SO, but this refers to a specific error, and I have referred to the relevant SO topics to solve this, but with no luck.
The code I have seeks to retrieve lines from a text file and read them into a dictionary. It works, but as you can see below, not completely.
File
"['a', 5]"
"['b', 2]"
"['c', 3]"
"['d', 0]"
Code
def readfiletodict():
with open("testfile.txt","r",newline="") as f:
mydict={} #create a dictionary called mydict
for line in f:
(key,val) = line.split(",")
mydict[key]=val
print(mydict) #test
for keys in mydict:
print(keys) #test to see if the keys are being retrieved correctly
readfiletodict()
Desired output:
I wish the dictionary to hold keys: a,b,c,d and corresponding values as shown in the file, without the unwanted character. Simiarly, I need the values to be stored correctly in the dictionary as integers (so that they can be worked with later)
For quick replication see: https://repl.it/KgQe/0 for the whole code and problem
Current (erroneous) output:
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
{'"[\'a\'': ' 5]"\r\n', '"[\'b\'': ' 2]"\r\n', '"[\'c\'': ' 3]"\r\n', '"[\'d\'': ' 0]"\r\n'}
"['a'
"['b'
"['c'
"['d'
The Stackoverflow answer I have used in my current code is from: Python - file to dictionary? but it doesn't quite work for me...