簡體   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