【问题标题】:Average of a nested dictionary嵌套字典的平均值
【发布时间】:2023-03-15 16:08:01
【问题描述】:

我有一个用于成绩册程序的嵌套字典,看起来像这样(这只是一个示例,可以是任意数量的学生或测试):

workDictionary = {'kevin': {'Test1': 97, 'Test2': 84, 'Test3': 89},
                  ''Bob':{'Test1': 67, 'Test2': 74, 'Test3': 59},
                  'carol':{'Test1': 47, 'Test2': 94, 'Test3': 79},
                  'ted':{'Test1': 67, 'Test2': 64, 'Test3': 99}}

我想得到最里面的值的平均值,例如:

finalGrade = {}
for k,v in workDictionary.iteritems():
    finalGrade[k] = sum(v)/ float(len(v))

但是还有其他因素,我正在使用酸洗和未定义数量的学生和测试。这是完整的程序:

# Modules
import pickle

def dumpPickle(fileName):
    pickle.dump(workDictionary, open(fileName,'wb'))
    return

def loadUnPickle(fileName):
    global workDictionary
    workDictionary = pickle.load(open(fileName, 'rb'))
    return(workDictionary)

workDictionary = {}
keys = workDictionary.keys()
values = workDictionary.values()

def myMenu():
    mySelect = -1
    while mySelect != 0:
        print("\n1. Open Dictionary File\n"+
              "2. Create/Write to a Dictionary\n"+
              "3. Add a New Student\n"+
              "4. Find a Student's Scores\n"+
              "5. Add a New Student Score\n"+
              "6. Display Dictionary Data\n"+
              "0. Exit\n"
              )
        mySelect = int(input("Enter Menu Number: "))
        if mySelect == 1:
            fileName = input("Enter file name")
            print("\nyour file is now open")
            loadUnPickle(fileName)

        elif mySelect == 2:
            fileName = input("please create a new file.")
            print("\nyour new file is now open")

        elif mySelect == 3:
                newStudent = input("Enter the new student's name")
                firstTest = input("Enter the name of the first test")
                testGrade = input("Enter the new student's first grade")
                addDictionary = {newStudent:{firstTest:testGrade}}
                workDictionary.update(addDictionary)
                print("\n" + newStudent + str(workDictionary[newStudent]))
                dumpPickle(fileName)

        elif mySelect == 4:
            print("\nEnter student name")
            myName = input()
            for name in workDictionary:
                if name == myName:
                    print("\n",workDictionary.get(myName))

        elif mySelect == 5:
            print("\nEnter student name ")
            myName = input()
            print("\nEnter assignment to add or update")
            myValue = input()
            for name in workDictionary:
                if name == myName:
                    newGrade = input("Enter new Grade")
                    workDictionary[name][myValue]= newGrade
                    dumpPickle(fileName)
                    print("\n" + name + str(workDictionary[name]))
        elif mySelect == 6:
            print(workDictionary)
    return

# Main Loop

我想添加另一个菜单选项,该选项取某个学生的平均值并显示它。

【问题讨论】:

  • 感谢到目前为止的答案,但我认为我的一些值被记录为字符串而不是整数。我去看看能不能解决这个问题。
  • 再次感谢大家的帮助,我们已经解决了。

标签: python dictionary average pickle


【解决方案1】:

这是我写的,但你可以重写它,这样在你的程序中会更好:

def student_avg(student):
    summ = 0
    grades_num = 0
    for test, grade in student.items():
        summ += grade
        # unless you aren't sure that grade would be a int, in which case add exception
        grades_num += 1
    average = summ / grades_num
    return average

average = student_avg(workDict["kevin"])

【讨论】:

  • 感谢您的帮助,我不得不将成绩变量更改为 int。之后它就像一个魅力。
【解决方案2】:

你可以使用字典理解

from statistics import mean
avg_grades = {name: mean(tests.values()) for (name, tests) in workDictionary.items()}

存储在 avg_grades 中的结果将是:

{'Bob': 66.66666666666667,
 'carol': 73.33333333333333,
 'kevin': 90.0,
 'ted': 76.66666666666667}

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2020-08-20
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多