简体   繁体   中英

How to store multiple values in a dictionary?

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

Looks like you expect stud_data to be a list of dictionaries and not a dictionary, so make it a list and use .append instead of .update .

Also:

  • You will need to shift things around if you actually indent to allow the user input multiple times.

  • You don't need flag . Use while True and break when needed

  • No need for parentheses around a single value


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 mentioned they are supposed to do lookups of students in the final step. One could search the list but I believe a dict is the better choice. I'd suggest:

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

Of course Kim will want to clean up the final print.

As it's said above, you could use a dictionary of lists. But instead of the break statement I would use the same "repeat" variable.

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

A dictionary that stores records of students, even if they have the same name:

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

Querying the dict:

name = input("Enter student name: ")

print(stud_data.get(name, "Record is not in the dictionary"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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