Hello everyone, I am trying to create a list of students:

first_name = [] source_name = [] dict1 = {} n = input("How many new students: ") for i in range(0, n): name = raw_input("Enter first name: ") s_n = raw_input("Enter second name: ") first_name.extend([name]) source_name.extend([s_n]) dict1['name'] = first_name dict1['source_name'] = source_name print dict1 

But for some reason, when I add more than one student, I only get the last student I added. Why?

  • I launched this code - all students are added as it should be, formulate the problem more clearly - andreymal
  • I only have the last student I add, and the first one is teaching. - max
  • They would explain (with a screenshot, for example) how you determine that there is only the last student, for I see all students in print dict1 - andreymal
  • Maybe he did not explain himself correctly, but everything seems to be working now, thanks anyway. - max

1 answer 1

A bad idea is to store lists of first and last names of students in a dictionary. You just need to keep a list of dictionaries and that's it. A dictionary is needed to represent a single entity as an object.

 students = [] n = input("How many new students: ") for i in range(0, n): name = raw_input("Enter first name: ") s_n = raw_input("Enter second name: ") students.append({'name': name, 'source_name': s_n}) print students 
  • Thanks helped! - max
  • The solution is correct, but the cause of the problem is not, because lists are written in the dictionary and there, in any way, there are all students :) - andreymal
  • @andreymal, but yes, but this is a bad idea to do so. - Klym