48_Read_file_contents_into_dict_alternative.py


Sign up Free. Don't forget to check out our challenges, lessons, solve and learn series and more ...


Code Snippet

"""File Contents
"['a', 5]"
"['b', 2]"
"['c', 3]"
"['d', 0]"
"""
def readfiletodict():
    with open("testfile.txt", "r") as f:
        mydict = {} #create a dictionary called mydict
        for line in f:
            key, val = line.strip("\"\n[]").split(",")
            mydict[key.strip("'")] = val.strip()
    print(mydict) #test
    for key in mydict:
        print(key) #test to see if the keys are being retrieved correctly


readfiletodict()
                    

Try it yourself