Initial commit: Python learning project with examples and exercises
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
#6.2.1
|
||||
# 创建一部字典来存储学生的信息
|
||||
students = {
|
||||
'001': {
|
||||
'name': 'Alice',
|
||||
'age': 20,
|
||||
'major': 'Computer Science',
|
||||
'grades': {'math': 90, 'science': 85, 'english': 92}
|
||||
},
|
||||
'002': {
|
||||
'name': 'Bob',
|
||||
'age': 22,
|
||||
'major': 'Electrical Engineering',
|
||||
'grades': {'math': 88, 'science': 90, 'english': 87}
|
||||
},
|
||||
'003': {
|
||||
'name': 'Charlie',
|
||||
'age': 19,
|
||||
'major': 'Mechanical Engineering',
|
||||
'grades': {'math': 95, 'science': 93, 'english': 88}
|
||||
}
|
||||
}
|
||||
|
||||
# 打印所有学生的信息
|
||||
for student_id, info in students.items():
|
||||
print(f"Student ID: {student_id}")
|
||||
print(f"Name: {info['name']}")
|
||||
print(f"Age: {info['age']}")
|
||||
print(f"Major: {info['major']}")
|
||||
print("Grades:")
|
||||
for subject, grade in info['grades'].items():
|
||||
print(f" {subject}: {grade}")
|
||||
print("")
|
||||
|
||||
# len():返回字典中键值对的数量。
|
||||
# str():返回字典的字符串表示形式。
|
||||
# dict.keys():返回一个视图对象,显示字典中的所有键。
|
||||
# dict.values():返回一个视图对象,显示字典中的所有值。
|
||||
# dict.items():返回一个视图对象,显示字典中的所有键值对。
|
||||
# dict.get(key, default=None):返回指定键的值,如果键不存在则返回默认值。
|
||||
# dict.pop(key, default=None):移除指定的键值对,并返回该键的值,如果键不存在则返回默认值。
|
||||
# dict.popitem():移除并返回字典中的最后一对键值对。
|
||||
# dict.update():使用另一个字典中的键值对更新当前字典。
|
||||
|
||||
|
||||
# 使用len()获取学生数量
|
||||
student_count = len(students)
|
||||
print(f"Total number of students: {student_count}")
|
||||
|
||||
# 使用str()获取字典的字符串表示
|
||||
students_str = str(students)
|
||||
print(f"String representation of students: {students_str}")
|
||||
|
||||
|
||||
# 使用dict.keys()获取所有学生的学号
|
||||
student_ids = students.keys()
|
||||
print(f"Student IDs: {student_ids}")
|
||||
print('here')
|
||||
# 使用dict.values()获取所有学生的信息
|
||||
student_infos = students.values()
|
||||
print(f"Student information: {student_infos}")
|
||||
|
||||
# 使用dict.items()获取所有学生的学号和对应信息
|
||||
student_items = students.items()
|
||||
print(f"Student items: {student_items}")
|
||||
|
||||
# 使用dict.get()获取某个学生的信息
|
||||
student_004 = students.get('004', 'Not found')
|
||||
print(f"Student 004: {student_004}")
|
||||
|
||||
# 使用dict.pop()移除一个学生的信息
|
||||
removed_student = students.pop('001')
|
||||
print(f"Pop student 001: {removed_student}")
|
||||
|
||||
# 使用dict.popitem()移除最后一对键值对
|
||||
last_student = students.popitem()
|
||||
print(f"Pop last student: {last_student}")
|
||||
Reference in New Issue
Block a user