使用相同的键在字典中添加值

时间:2020-06-13 22:47:37

标签: python class dictionary key

我正在努力将文本文件导入字典。该文件包含学生ID和他们迄今所学的学时数。一旦为学生创建了一个班级并打开字典,我就无法弄清楚如何将共享相似键的值相加。

class Student(object):

    def __init__(self, ID, hours):
        self.id = id
        self.hours = hours

        d = {}
        stud = open("students.txt", "r")
        for line in stud:
            line = line.strip()
            new_file = line.split(",")
            d[stud[0]] = Student(stud[0], stud[1])

现在我被卡住了吗?

2 个答案:

答案 0 :(得分:0)

此代码现在对我有用。

d = {}

class Student:
    def __init__(self, id, hours):
        self.id = id
        self.hours = hours

with open('filename.csv') as f:
    for line in f:
        stu = (line.strip()).split(',')
        d[stu[0]] = Student(stu[0], stu[1])

print(d)

答案 1 :(得分:0)

此帮助:

class Student(object):

    def __init__(self, ID, hours):
        self.id = id
        self.hours = hours

        d = {}
        with open("students.txt", "r") as stud:

            s = [l.strip().split(",") for l in stud.readlines()]

            if stud[0] not in d.keys(): # If the student is not yet in the dictionary
                d[stud[0]] = Student(stud[0], stud[1]) # Add the student
            else: # If already in
                d[stud[0]].hours += stud[1] # Add the hours to that student's hours