以下是我一直在尝试的示例代码段。
例如
my_dict = {}
my_dict = []
new_dict = {}
student_id = input("Enter id: ")
name = raw_input("Enter name: ")
course = raw_input("Enter course: ")
school = raw_input("Enter school: ")
new_dict['student_id'] = student_id
new_dict['name'] = name
new_dict['course'] = course
new_dict['school'] = school
my_dict[student_id].append( new_dict )
此代码会产生错误。
如何提出这个预期的输出? 关键是student_id。
output = [{
'1': {
'student_id': '1',
'name': 'Test Name 1',
'course': 'Course 1',
'school':'School 1'
},
'2': {
'student_id': '2',
'name': 'Test Name 2',
'course': 'Course 2',
'school': 'Schoole 2'
},
}]
答案 0 :(得分:0)
我相信你正在混淆列表和字典功能。
从你想要的输出看起来你想要一个字典而不是一个列表,你的例子中的最后一行需要像这样改变:
my_dict = {}
new_dict = {}
student_id = input("Enter id: ")
name = raw_input("Enter name: ")
course = raw_input("Enter course: ")
school = raw_input("Enter school: ")
new_dict['student_id'] = student_id
new_dict['name'] = name
new_dict['course'] = course
new_dict['school'] = school
my_dict[student_id] = new_dict
答案 1 :(得分:0)
你不能'追加'到字典。你只能'更新'它。
而不是window
尝试my_dict[student_id].append( new_dict )