如何在不覆盖第一个值的情况下为键添加值?下面是我的代码示例:
def course_rolls(records):
"""Maps course code to the student ID"""
course_to_id_dict = {}
for record in records:
course = record[0][0]
student_id = record[1][0]
course_to_id_dict[course] = {student_id}
print(course_to_id_dict)
return course_to_id_dict
records = [(('MTH001', 'Mathematics 1'),
(2763358, 'Cooper', 'Porter')),
(('EMT003', 'Mathematical Modelling and Computation'),
(2788579, 'Mandi', 'Stachowiak'))]
rolls = course_rolls(records)
expected = {'MTH001': {2763358}, 'EMT003': {2788579}}
print(rolls==expected)
输出为真
假设一个学生ID与同一个键映射,并且我希望输出是预期的:
rolls = course_rolls(records)
records = [(('MTH001', 'Mathematics 1'),
(2763358, 'Cooper', 'Porter')),
(('EMT003', 'Mathematical Modelling and Computation'),
(2788579, 'Mandi', 'Stachowiak')),
(('MTH001', 'Mathematics 1'),
(2763567, 'New', 'Value'))]
rolls = course_rolls(records)
expected = {'MTH001': {2763358,2763567}, 'EMT003': {2788579}}
print(rolls==expected)
您需要检测到键已经存在于} 为您提供一个空的集。你知道吗
course_to_dict_id
中并添加到该集中,或者在尝试检索尚未设置的键时使用^{后者更为简洁:
这将生成
{'MTH001': {2763358, 2763567}, 'EMT003': {2788579}}
作为输出(字典中的每个值都是一个包含1个或多个整数的集合)。你知道吗相关问题 更多 >
编程相关推荐