Updating Dictionary in a loop Python

时间:2018-04-18 18:01:53

标签: python

I am creating records in dict data type in python. How can I add new items in the dict by using while loop as we do in tuples by using:

 tuple += (rec)

When I use this code it will add elements in the tuple no matter how much. How to perform the same task with a dict

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

1 个答案:

答案 0 :(得分:0)

To add to a dict named stdrecs, you would store a new key/value pair, i.e stdrecs[name] = courses. This would look like:

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