Search code examples
pythonfiledictionarycollectionsdefaultdict

Is there a way to add a file which has similar ids to a dictionary?


I am retrieving grades from a file and I want to insert them to a dictionary with the id as key, what is the best way to do this? Below is the code.

from HW08_Swayam_Shah import file_reader
import os
from collections import defaultdict
def grades(path):
    l= defaultdict()
    g = {"A":4.0,"A-":3.75,"B+":3.25,"B":3.0,"B-":2.75,"C+":2.25,"C-":0,"D+":0,"D":0,"D-":0,"F":0}
    for id, course, grade, prof_id in file_reader(
            os.path.join(path, "g.txt"), fields=4, sep='|', header=False):
        for k,v in g.items():
            if grade==k:
                l[id].append(v)
    return l
x = grades("C://Users/Documents/Downloads")
print(x)

Below is the input file I am using:

10103|SSW 567|A|98765
10103|SSW 564|A-|98764
10103|SSW 687|B|98764

As you can see the first field is similar for all columns, but I need this to be my key. Obviously the dictionary will throw a key error, but when the key is same I want it to add it to the next value. Something like:

{10103:{A,A-,B}}

How can I achieve this?


Solution

  • You need to specify the factory for the defaultdict:

    l = defaultdict(list)
    

    This will create an empty list if the dictionary item doesn't exist, then append() will work.

    You don't need to loop over the dictionary g. Since grade is a key, just use g[grade] to get the value.

    def grades(path):
        l= defaultdict(list)
        g = {"A":4.0,"A-":3.75,"B+":3.25,"B":3.0,"B-":2.75,"C+":2.25,"C-":0,"D+":0,"D":0,"D-":0,"F":0}
        for id, course, grade, prof_id in file_reader(
                os.path.join(path, "g.txt"), fields=4, sep='|', header=False):
            grade_numeric = g[grade]
            l[id].append(grade_numeric)
        return l