You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典添加多个元素时新元素覆盖旧元素的问题求助

问题分析与解决

问题根源

你的代码里,每次调用StudentGradeBook函数时,都会重新初始化grade_book字典:

grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}

这意味着每次添加新学生,都是在初始的Tom和Bob基础上添加,而不是在上一次添加后的字典上继续操作。所以第二次添加Thomas时,之前的Bill会被覆盖,因为字典又回到了初始状态。

修复方案

有两种简单的修复方式:

方案一:使用全局字典

把成绩字典移到函数外部,作为全局变量,让StudentGradeBook直接修改这个全局字典:

# 全局成绩字典,只初始化一次
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}

def AddStudent():
    again = 'y'
    while again.lower() == 'y':
        student_key = input("What's the name of the student? ")
        n = int(input('How many grades do you wish to input? '))
        grades = []
        for i in range(n):
            grade = int(input(f'Grade {i + 1}: '))
            grades.append(grade)
        StudentGradeBook(student_key, grades)
        again = input('Do you wish to add another student? (y) ')
    
def StudentGradeBook(name, grade_value):
    global grade_book  # 声明使用全局变量
    grade_book[name] = grade_value
    print(grade_book)

方案二:在AddStudent中维护字典

直接把字典的初始化和修改都放在AddStudent函数里,去掉多余的StudentGradeBook函数,逻辑更紧凑:

def AddStudent():
    # 初始化成绩字典,只执行一次
    grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
    again = 'y'
    while again.lower() == 'y':
        student_key = input("What's the name of the student? ")
        n = int(input('How many grades do you wish to input? '))
        grades = []
        for i in range(n):
            grade = int(input(f'Grade {i + 1}: '))
            grades.append(grade)
        # 直接向字典添加新学生
        grade_book[student_key] = grades
        print(grade_book)
        again = input('Do you wish to add another student? (y) ')

# 运行函数
AddStudent()

修复后运行效果

添加Bill和Thomas后,输出会包含所有学生:

What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n

内容的提问来源于stack exchange,提问作者Alfonso Martine Petz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:35:20