如何在字典中存储多个值?

3

如何在字典中存储多个值?


stud_data 中使用Name作为键。 - Wups
1
@哎呀,那只有在确保名称唯一的情况下才能正常工作(而这在实际应用中并不是这样的)。 - DeepSpace
4个回答

3
看起来你期望 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)

3

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"))

当然,金会想要清理最终版本的印刷文件。


@DeepSpace:是的,这里没有尝试智能处理碰撞。然而,这是一个初学者的问题。我觉得现在没有必要增加那种复杂度水平。 - jim washer

2

如上所述,您可以使用列表字典。 但是,我会使用相同的“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)`

2

一个字典,即使学生姓名相同也可以存储他们的记录:

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"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接