Write items to a dictionary from a file python

I am trying to write lists from a file and define them to separate values in a dictionary. The text file would look something like this:

[12, 13, 14]
[87, 45, 32]
...

and then the dictionary would look something like this:

{"score_set0": [12, 13, 14], "score_set1": [87, 45, 32]...}

This is the code I have get so far, but it just returns an empty dictionary

def readScoresFile(fileAddr):
    dic = {}
    i = 0
    with open(fileAddr, "r") as f:
        x = len(f.readlines())
        for line in f:
            dic["score_set{}".format(x[i])] = line
            i += 1
    return dic

I am only programming at GCSE level (UK OCR syllabus if that helps) in year 10. Thanks for any help anyone can give

Also I am trying to do this without pickle module

>Solution :

x = len(f.readlines()) consumed your whole file, so your subsequent loop over f is iterating an exhausted file handle, sees no remaining lines, and exists immediately.

There’s zero need to pre-check the length here (and the only use you make of x is trying to index it, which makes no sense; you avoided a TypeError solely because the loop never ran), so just omit that and use enumerate to get the numbers as you go:

def readScoresFile(fileAddr):
    dic = {}
    with open(fileAddr, "r") as f:
        for i, line in enumerate(f):  # Let enumerate manage the numbering for you
            dic["score_set{}".format(i)] = line  # If you're on 3.6+, dic[f'score_set{i}'] = line is nicer
    return dic

Note that this does not actually convert the input lines to lists of int (neither did your original code). If you want to do that, you can change:

dic[f'score_set{i}'] = line

to:

dic[f'score_set{i}'] = ast.literal_eval(line)  # Add import ast to top of file

to interpret the line as a Python literal, or:

dic[f'score_set{i}'] = json.loads(line)  # Add import json to top of file

to interpret each line as JSON (faster, but supports fewer Python types, and some legal Python literals are not legal JSON).

As a rule, you basically never want to use .readlines(); simply iterating over the file handle will get you the lines live and avoid a memory requirement proportionate to the size of the file. (Frankly, I’d have preferred if they’d gotten rid of it in Py3, since list(f) gets the same result if you really need it, and it doesn’t create a visible method that encourages you to do "The Wrong Thing" so often).

By operating line-by-line, you eventually store all the data, but that’s better than doubling the overhead by storing both the parsed data in the dict and all the string data it came from in the list.

Leave a Reply