python在循环中更新字典

Updating Dictionary in a loop Python

本问题已经有最佳答案,请猛点这里访问。

我正在用python在dict数据类型中创建记录。如何使用while循环在dict中添加新项目,就像在tuples中那样,使用:

1
 tuple += (rec)

当我使用此代码时,它将在tuple中添加元素,无论添加多少。如何使用dict执行相同的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while True:
    name = input('Student Name: ')
    while True:
        course = input('Course Name: ')
        courses.append(course)
        print('You have entered', len(courses), 'course(s)')
        ch_course = input('Would you like to add a new course [Y]or[N]: ')
        if ch_course == 'y' or ch_course == 'Y':
            continue
        else:
            stdrec = ({name : courses})
            break
    ch_name = input('Would you like to add a new record [Y]or[N]: ')
    if ch_name == 'n' or ch_name == 'N':
        print(stdrec)
        break

要添加到名为stdrecsdict中,需要存储一个新的键/值对,即stdrecs[name] = courses。如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
stdrecs = {}    
while True:
    name = input('Student Name: ')
    courses = []
    while True:
        course = input('Course Name: ')
        courses.append(course)
        print('You have entered', len(courses), 'course(s)')
        ch_course = input('Would you like to add a new course [Y]or[N]: ')
        if ch_course.upper() == 'Y':
            continue
        else:
            stdrecs[name] = courses
            break
    ch_name = input('Would you like to add a new record [Y]or[N]: ')
    if ch_name.upper() == 'N':
        print(stdrecs)
        break