【问题标题】:Adding values in a dictionary with the same key在具有相同键的字典中添加值
【发布时间】:2020-06-13 22:47:37
【问题描述】:

我正在将文本文件导入字典。该文件有学生 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])

现在我卡住了?

【问题讨论】:

  • 您要添加小时数吗?还是要保存多个具有相同 ID 的学生对象?
  • 抱歉,是的,如果每个学生在我的文件中出现多次(有些人会这样做),我需要获取每个学生 ID,然后添加每个学生的总小时数。我认为已经有人帮助回答了我的问题,尽管时间显示不正确。感谢您的帮助!

标签: python class dictionary key


【解决方案1】:

这段代码现在对我有用。

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)

【讨论】:

  • 天哪,我认为这确实有效!我怎么会打印 d 小时不显示呢?相反,我得到了学生 ID,然后是“<_main__.student object at>”
  • 如果你想获取你使用的对象的属性 Student.__dict__ 但你在这里并不需要一个类。您可以将 id 和 hours 作为键和值附加到字典中。当你打印一个对象时,它会打印它的内存位置而不是它的属性。
  • 您能详细说明一下吗?我创建了一个类,因为我还创建了一个函数来计算时间。当我尝试调用我的函数时,我看不到小时总数并且正在获取内存位置。我试图对您的代码进行调整,但我所做的不再是将相同的键组合在一起!感谢您的帮助:)
【解决方案2】:

这会有帮助吗:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2013-02-16
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多