【问题标题】:How do I properly add to a dict from user input and print the dict with a for loop?如何从用户输入正确添加到字典并使用 for 循环打印字典?
【发布时间】:2020-06-13 00:20:36
【问题描述】:

一段时间以来,我一直在尝试获取用户输入并将其添加到现有字典中。然后使用 for 循环打印字典键和值,但我无法弄清楚执行此操作的正确方法。

经过研究,我几乎可以肯定我没有正确地将用户输入的值添加到 dict 中,并且当代码运行时,我收到一条错误消息,指出“set”是可下标的。我应该如何将用户数据添加到字典并正确打印?

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

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    您希望students 中的每个项目本身都是字典(因此students 是字典字典)。要做到这一点,你需要改变

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

    类似

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

    正如目前所写,您正在创建 set {student_id, student_age, student_grade} 而不是 dict

    【讨论】:

      【解决方案2】:

      改成

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

      这个

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

      【讨论】:

        【解决方案3】:

        您需要为字典中的每个值提供正确的键:

        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)
        

        改变这个(这是一个set):

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

        对此(这是一个key-value配对dict):

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-12
          • 2021-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-23
          • 1970-01-01
          • 2016-07-06
          相关资源
          最近更新 更多