简体   繁体   English

如何从用户输入正确添加到字典并使用 for 循环打印字典?

[英]How do I properly add to a dict from user input and print the dict with a for loop?

I have been trying for some time now to take user input and add it to an existing dictionary.一段时间以来,我一直在尝试获取用户输入并将其添加到现有字典中。 Then print the dictionary keys and values with a for loop but I can't figure out the proper way to do this.然后使用 for 循环打印字典键和值,但我无法找出正确的方法来执行此操作。

After research I am almost certain I am not adding the user inputted values to the dict correctly and when the code is run i get an error stating that 'set' is subscriptable.经过研究,我几乎可以肯定我没有正确地将用户输入的值添加到字典中,并且当代码运行时,我收到一条错误消息,指出“set”是可下标的。 How should I add the user data to the dict and also print it properly?我应该如何将用户数据添加到字典并正确打印?

# Authorized Users
authorized_users = ["Jim","Mary","Claire","Hector","Ren"]

# Student Dictionary
students ={
    "Alice":{"id": "1", "age":26, "grade":"A"},
    "Bob":{"id": "2", "age":34, "grade":"C"},
    "Jimbo":{"id": "3", "age":12, "grade":"B"},
    "Karen":{"id": "4", "age":33, "grade":"D"},
    "Keith":{"id": "5", "age":53, "grade":"F"}
    }


while True:
    login = input("Please login with an authorized user: ").strip().title()

    if login in authorized_users:
        print("\nWelcome back "+login+", please choose an option from the menu!")

        print(
            '''
            1.) View Student List
            2.) View Authorized Users
            3.) Add student
            4.) Remove Student
            5.) Exit program
            '''
             )

        authorized_input = int(input("Select an option from the list above to proceed.: "))

        if authorized_input == 1:
            print("\n*** ACTIVE STUDENTS ***")
            for student_id, student_info in students.items():
                print("\nName:", student_id)
                for key in student_info:
                    print(key + ':', student_info[key])      
            print("\n")


        elif authorized_input == 2:
            print("\n*** AUTHORIZED USERS ***")
            for x in range(len(authorized_users)):
                print(authorized_users[x])

            print("\n")

        elif authorized_input == 3:
            print("Please fill in the new students information")

            student_name = input("Enter the student's name: ")
            student_id = input("Enter the student's ID: ")
            student_age = input("Enter the student's age: ")
            student_grade = input("Enter the student's grade: ")

            # Add data to dict students
            students[student_name] = {student_id, student_age, student_grade}

            for student_id, student_info in students.items():
                print("\nName:", student_id)
                for key in student_info:
                    print(key + ':', student_info[key])  
            print("\n")


        elif authorized_input == 4:
            print("option 4")

        elif authorized_input == 5:
            quit()

    else:
        print("access denied")

Change this to将此更改为

students[student_name] = {student_id, student_age, student_grade}

this这个

students[student_name] = {'id': student_id, 'age': student_age, 'grade': student_grade}

You are expecting each item in students to be a dictionary itself (so students is a dictionary of dictionaries).您期望students中的每个项目本身都是字典(因此students是字典的字典)。 To do that, you need to change为此,您需要更改

students[student_name] = {student_id, student_age, student_grade}

to something like类似于

students[student_name] = {
    'id': student_id, 
    'age': student_age, 
    'grade': student_grade
}

As currently written, you are creating a set {student_id, student_age, student_grade} instead of a dict .如当前所写,您正在创建一个set {student_id, student_age, student_grade}而不是dict

You need to give the proper keys to each value in the dict:您需要为字典中的每个值提供正确的键:

students ={
    "Alice":{"id": "1", "age":26, "grade":"A"},
    "Bob":{"id": "2", "age":34, "grade":"C"},
    "Jimbo":{"id": "3", "age":12, "grade":"B"},
    "Karen":{"id": "4", "age":33, "grade":"D"},
    "Keith":{"id": "5", "age":53, "grade":"F"}
    }

student_name = 'DirtyBit'
student_id = '12345'
student_age = 22
student_grade = 'A'
students[student_name] = {'id': student_id, 'age': student_age, 'grade': student_grade}

print(students)

Change this (which is a set ):改变这个(这是一个set ):

students[student_name] = {student_id, student_age, student_grade}

to this (which is a key-value paired dict ):对此(这是一个key-value配对dict ):

students[student_name] = {'id': student_id, 'age': student_age, 'grade': student_grade}

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

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