How to add to python dictionary dynamic input

I searched stackoverflow and online and did not find an answer to this question.

My dictionary keeps replacing the values instead of inserting new one because I use a loop. I am accepting input from a user in a loop and inserting it into my dictionary but it keeps replacing. It only overwrites when I use a loop, without a loop it is ok but I need the loop and I need a specific format, not any random key and any random value (seem to be the majority of python responses).

I need output to be exactly like this: [{‘firstname’: Roger, ‘lastname’: Smith, ‘major’: history}, {‘firstname’: Rodrigo, ‘lastname’: Sandoval, ‘major’: physics}]

This is my code, what am I doing wrong? Thanks

studentsD = {}
studentsList = []

while more values to enter:        
    firstname = input('Enter firstname')
    lastname = input('Enter lastname')
    major = input('Enter major')          
   
    studentsD['firstname'] = firstname
    studentsD['lastname']=lastname
    studentsD['major']=major

    studentList.append(studentsD)   # problem here  
            

end loop

Answer

The data structure you describe in your desired output is a list, not a dictionary, there is no key-value structure. In the dictionary you always overrite the three values for the three keys.

For your desired output you’d create a second student list and put a dictionary in it for every student.

student_data_list = []

while ...:

    firstname = input('Enter firstname')
    lastname = input('Enter lastname')
    major = input('Enter major')          
   
    student = {}
    student['firstname'] = firstname
    student['lastname']=lastname
    student['major']=major
    student_data_list.append(student)

As an alternative you could add a student id and have that as your key for the student dictionary. Then you can increment it in the loop for every student and add the student-dictionary with that ID as key.

id = 0

while ...:

    firstname = input('Enter firstname')
    lastname = input('Enter lastname')
    major = input('Enter major')          
   
    student = {}
    student['firstname'] = firstname
    student['lastname']=lastname
    student['major']=major
    studentsD[id] = student
    id++