如何在字典中存储多个值?
stud_data
是一组字典列表而不是一个字典,因此需要将其改为列表并使用 .append
而不是 .update
。flag
,可使用 while True
并在需要时使用 break
。
- 单个值周围不需要括号。stud_data = []
while True:
Name = input("Enter the student name :")
Age = input("Enter the age :")
Gender = input("Enter the {} grade :")
repeat = input("Do you want to add input more?: ")
stud_data.append({
"Name": Name,
"Age": Age,
"Gender": Gender
})
if repeat == "no" or repeat == "NO":
break
print(stud_data)
Kim提到,最后一步他们应该对学生进行查找。虽然可以搜索列表,但我认为字典是更好的选择。我建议使用:
stud_data = {}
while True:
name = input("Enter the student name :")
age = input("Enter the age :")
gender = input("Enter the {} grade :")
repeat = input("Do you want to add input more?: ")
stud_data[name] = {'age': age, 'gender': gender}
if repeat.lower() == "no":
break
searched_name = input("Enter name to lookup :")
print(searched_name,stud_data.get(searched_name,"Record is not in the dictionary"))
当然,金会想要清理最终版本的印刷文件。
如上所述,您可以使用列表字典。 但是,我会使用相同的“repeat”变量,而不是使用break语句。
`stud_data = {"Name": [],
"Age": [],
"Gender": []}
repeat = 'yes'
while repeat == "yes" or repeat == "YES":
print(repr(repeat))
Name = input("Enter the student name :")
Age = input("Enter the age :")
Gender = input("Enter the {} grade :")
repeat = input("Do you want to add input more?: ")
stud_data['Name'].append(Name)
stud_data['Age'].append(Age)
stud_data['Gender'].append(Gender)
print(stud_data)`
一个字典,即使学生姓名相同也可以存储他们的记录:
stud_data = {}
while True:
Name = input("Enter the student name :")
Age = input("Enter the age :")
Gender = input("Enter the grade :")
repeat = input("Do you want to add input more?: ")
if not Name in stud_data:
stud_data[Name] = []
stud_data[Name].append({
"Name": Name,
"Age": Age,
"Gender": Gender
})
if repeat == "no" or repeat == "NO":
break
查询字典:
name = input("Enter student name: ")
print(stud_data.get(name, "Record is not in the dictionary"))
stud_data
中使用Name
作为键。 - Wups