繁体   English   中英

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

[英]How to store multiple values in a dictionary?

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

看起来您希望stud_data是字典列表而不是字典,因此将其.update列表并使用.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 提到他们应该在最后一步查找学生。 可以搜索列表,但我相信 dict 是更好的选择。 我建议:

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

当然,Kim 会想要清理最终的印刷品。

如上所述,您可以使用列表字典。 但是我会使用相同的“重复”变量而不是 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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM