简体   繁体   English

如何在字典中存储输入的信息?

[英]How can I store inputted information in a dictionary?

I want to ask the user for a student and their corresponding ID number, adding them to the dictionary. 我想询问用户一个学生及其相应的ID号,然后将其添加到词典中。 But if the user wants to add another student, I'm not sure how to add to the dictionary instead of replacing the other student. 但是,如果用户想添加另一个学生,则不确定如何添加到词典中而不是替换另一个学生。 Currently, my code replaces the previous student instead of adding another key and item to the database of students. 目前,我的代码代替了以前的学生,而不是向学生的数据库中添加了另一个键和项。 How can I add another student and their ID to the database/dictionary? 如何将另一个学生及其ID添加到数据库/词典中?

while input("Would you like to add a student? ") == "yes":
    name = input("What is the student's name?: ")
    ID = input("What is the student's ID?: ")
    nameID = {ID: name}
    for ID in nameID.keys():
        print(nameID)
else:
    print(nameID)

The reason that you are not getting the expected output is every time you create a new student you also create a new dict. 未能获得期望的输出的原因是每次创建新学生时,也会创建新字典。 Therefore, if you just append the student to an existing dict you will avoid the problem your are having. 因此,如果只是将学生添加到现有字典中,则可以避免遇到的问题。

nameID = {}

while input("Would you like to add a student? ") == "yes":
    name = input("What is the student's name?: ")
    ID = input("What is the student's ID?: ")
    nameID[ID] = name
    for ID in nameID.keys():
        print(ID)
else:
    print(nameID)

Your line 你的线

nameID = {ID: name}

creates a dictionary, again and again, inside that loop. 在该循环内一次又一次创建字典。 Create an empty dictionary 创建一个空字典

nameID = {}

first, and then add items to it inside the loop: 首先,然后在循环内向其中添加项目:

nameID[ID] = name

You also don't need to loop over nameID.keys() to print them. 您也不需要遍历nameID.keys()即可打印它们。 You probably meant 你可能是说

for id in nameID:
    print (id,nameID[id])

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

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