2017-05-28 67 views
1

如何在不覆盖第一个值的情况下为键添加值?下面是我的代码示例:为词典增加更多值python 3

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) 

输出为True

比方说,如果一个学生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) 

回答

0

您需要检测密钥是否已存在于course_to_dict_id并添加到该集合,或者使用dict.setdefault()为您提供空集集合,只要您尝试检索尚未设置的密钥。

后者更简洁:

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个以上的整数)。

+0

但是,如果我写道course_to_id_dict [course] .append({student_id})不起作用 –

+0

@AsyrawiAbdullahZawawi:'course_to_id_dict [course]'不是一个列表,它是一个设置对象(假设该对象存在)。 'course_to_id_dict [course] .add(student_id)'会起作用,只要你首先测试'course'是否是现有的密钥。 –