为字典python3添加更多值

2024-06-26 14:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在不覆盖第一个值的情况下为键添加值?下面是我的代码示例:

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)

Tags: toidrecordstudentdictexpectedprintrolls
1条回答
网友
1楼 · 发布于 2024-06-26 14:15:35

您需要检测到键已经存在于course_to_dict_id中并添加到该集中,或者在尝试检索尚未设置的键时使用^{}为您提供一个空的集。你知道吗

后者更为简洁:

for record in records:
    course = record[0][0]
    student_id = record[1][0]
    course_to_id_dict.setdefault(course, set()).add(student_id)

这将生成{'MTH001': {2763358, 2763567}, 'EMT003': {2788579}}作为输出(字典中的每个值都是一个包含1个或多个整数的集合)。你知道吗

相关问题 更多 >