MST

星途 面试题库

面试题:Python中使用字典存储类似对象的基本技巧

假设有多个学生对象,每个学生对象具有姓名、年龄和成绩属性,如何使用Python字典来存储这些学生对象,并能方便地通过姓名获取对应的年龄和成绩信息?请写出实现代码并简要解释思路。
31.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
# 创建一个空字典用于存储学生信息
students_dict = {}

# 假设存在多个学生对象,这里以手动添加为例
student1 = {'name': 'Alice', 'age': 20,'score': 85}
student2 = {'name': 'Bob', 'age': 21,'score': 90}

# 将学生信息添加到字典中,以姓名作为键
students_dict[student1['name']] = {'age': student1['age'],'score': student1['score']}
students_dict[student2['name']] = {'age': student2['age'],'score': student2['score']}

# 通过姓名获取对应学生的年龄和成绩
name_to_find = 'Alice'
if name_to_find in students_dict:
    student_info = students_dict[name_to_find]
    print(f"姓名: {name_to_find}, 年龄: {student_info['age']}, 成绩: {student_info['score']}")
else:
    print(f"未找到名为 {name_to_find} 的学生")

思路解释

  1. 创建字典:首先创建一个空字典 students_dict,用于存储所有学生的信息。
  2. 添加学生信息:假设已有学生对象(这里手动创建简单的学生信息字典模拟),以学生的姓名作为字典的键,以包含年龄和成绩的子字典作为值,添加到 students_dict 中。
  3. 获取信息:通过指定姓名作为键,从 students_dict 中获取对应的子字典,从而获取该学生的年龄和成绩信息。若指定姓名不存在于字典中,则提示未找到。