I'm trying to take in the information of all the students in the school using nested dictionary. But when I try to assign the user defined value into the inner dictionary's key, it returns type error.
All the information is in a dictionary where the inner dictionary is for each "class" of the school. Here is the minimum reproducible example
#n is the number of classes in the school
n=2
school_info = {}
for j in range(1, n 1):
school_info[j] = input("name of the class:-")
for i in range(0, 2):
if i == 0:
k = "student_name :-"
elif i == 1:
k = "roll_number"
school_info [j][i] = input(k)
TypeError: 'str' object does not support item assignment
But there is no string that is being assigned another value. school_info[j][i]
is the inner dictionary's key for which the value is user defined.
CodePudding user response:
The result of evaluating this
school_info[j] = input("name of the class:-")
Will not allow you to later do this:
school_info [j][i] = input(k)
Because school_info[j]
will be a str
(the return value of calling input
) and not a dict
.
It seems like you want to use nested dictionaries here, so maybe what you want instead is something like this:
for j in range(1, n 1):
answer = input("name of the class:-")
school_info[answer] = {}
for i in range(0, 2):
if i == 0:
k = "student_name :-"
elif i == 1:
k = "roll_number"
school_info[answer][i] = input(k)
This is, admittedly, a guess, based on what you have and you may find other ways to achieve what you want after you have something that works.