Python函数打印字典值异常:仅输出最后一组值的问题排查
问题原因分析与修复方案
嘿,我一眼就揪出问题的根源啦!
核心问题:字典键的唯一性
在Python中,字典的键是唯一不可重复的。你看你定义的两个字典:
dictionary = { "grades": "O", "grades": "E", "grades": "A", # ... 后面的键都是"grades" } dictionary_means = { "means": "O is for Outstanding!...", "means": "E is for Exceeds Expectations!...", # ... 后面的键都是"means" }
每次你用同一个键(比如"grades")赋值时,后面的值会直接覆盖前面的。所以最终你的两个字典里其实只保留了最后一组键值对:dictionary只剩{"grades": "T"},dictionary_means只剩{"means": "T is for Troll. Wow, you're an idiot."}——这就是为什么遍历只输出最后一组值的原因!
修复方案
我们需要调整字典的结构,让每个等级对应唯一的键,这样才能存储所有的等级和描述。这里提供两种常见的修复方式:
方式1:让等级作为字典的键
把等级(O、E、A等)设为键,对应的描述作为值,这样结构更清晰,也方便关联等级和描述:
# 存储等级与对应名称(可选,如果你需要单独存等级的话) grade_levels = { "O": "Outstanding", "E": "Exceeds Expectations", "A": "Acceptable", "P": "Poor", "D": "Dreadful", "T": "Troll" } # 存储每个等级的详细描述 grade_descriptions = { "O": "O is for Outstanding! You're top level now!", "E": "E is for Exceeds Expectations! Very well done, almost perfect!", "A": "A for Acceptable. That's okay, hopefully it'll get you somewhere...", "P": "P is for Poor. Is that the best you can do?", "D": "D is for Dreadful. Well at least it's not T...", "T": "T is for Troll. Wow, you're an idiot." } def print_grades(grades): for grade, name in grades.items(): print(f"Your grade is {grade} ({name}).") def print_descriptions(descriptions): for desc in descriptions.values(): print(desc) # 直接调用函数即可,不需要print函数调用(因为函数没有返回值,print会输出None) print_grades(grade_levels) print_descriptions(grade_descriptions)
方式2:用列表存储多个字典(如果需要保留原有的键名结构)
如果你想保留grades和means作为键名,可以用列表来存储每一组数据:
grade_list = [ {"grades": "O", "means": "O is for Outstanding! You're top level now!"}, {"grades": "E", "means": "E is for Exceeds Expectations! Very well done, almost perfect!"}, {"grades": "A", "means": "A for Acceptable. That's okay, hopefully it'll get you somewhere..."}, {"grades": "P", "means": "P is for Poor. Is that the best you can do?"}, {"grades": "D", "means": "D is for Dreadful. Well at least it's not T..."}, {"grades": "T", "means": "T is for Troll. Wow, you're an idiot."} ] def print_all_grades(grade_list): for item in grade_list: print(f"Your grade is {item['grades']}. {item['means']}") print_all_grades(grade_list)
额外小提示
你原来的代码里print(owls_grades(dictionary))会额外输出None,因为你的函数没有return语句,默认返回None。直接调用函数就行,不需要用print包裹哦!
内容的提问来源于stack exchange,提问作者MikaLand
相关产品推荐
相关产品推荐

