Using Keys Method to Edit All Fields¶
Download the starter code and get it to run. It should ask you to change the fields in the student dictionary, but it won’t actually change anything.
What you should see¶
Please enter new values for the following:
student_id: 12
name: Johnny
grade: 11
average: 95
STUDENT INFO:
student_id: 123
name: John
grade: 10
average: 88.0
What you should do¶
In the first loop, after you get
new_valuefrom the user, assign it to its proper place in the dictionary. Use thekeyvariable to access the appropriate field. The program should show the following:Please enter new values for the following: student_id: 555 name: Goku grade: 99 average: over 9000 STUDENT INFO: student_id: 555 name: Goku grade: 99 average: over 9000
Let’s pretend that we don’t want the
student_idto be changed. In the loop, prevent that field from being changed. Use thecontinuestatement to skip to the next loop iteration if thekeyis"student_id".You will notice that all new values come in as strings and therefore will change the grade and average for the student to strings. We don’t want this. Use an if statement in the input-loop to check the type of each original item and do the appropriate conversion before saving the new value to the dictionary.
if type(student[key]) is int: # convert the new value to an int.
The types to check for are
str,int, andfloat. Use theint()andfloat()functions to do the conversions if necessary.
©2021 Daniel Gallo
This work is licensed under Attribution-NonCommercial-ShareAlike 4.0 International