简体   繁体   中英

Creating a dictionary with multiple user input choices in python

I am creating a dictionary in python in which a user enters his information, such as name and role. Regarding the last two keys, I would like the user to write a simple letter in the input that corresponds exactly to the options I provide.

Example:

`userData= dict() userData["name"]=input("Insert your name and last name: ") userData["role"]=input("What is your role? \nA)Professor \nB) Student [A/B]: ")

#print(userData)`

Then below I'd like to create if statements where if the user enters "A" in the role key, it saves the value as "Professor" in the dictionary, and if he/she/them enters "B" it saves the value as "Student". I tried writing something like this:

if userData["role"]== "A": userData["role"]== "Professor"

Only, in the dictionary, the value that is saved is "A" and not "Professor". How can I get the value I want by making the user type only one letter? Thank you in advance

PS: i'm completely new in Python and this is only an exercise class, please be gentle.

Possible solution is the following:

userData= {}
userData["name"]=input("Insert your name and last name: ")

# start infinite loop until correct role will be entered
while True:
    role=input("What is your role? \nA) Professor \nB) Student\n").upper()
    if role == 'A':
        userData["role"] = "Professor"
        break
    elif role == 'B':
        userData["role"] = "Student"
        break
    else:
        print(f"{role} is incorrect role. Please enter correct role A or B")
        continue

print(userData)

Prints

Insert your name and last name: Gray
What is your role? 
A) Professor 
B) Student 
B
{'name': 'Gray', 'role': 'Student'}

Another solution that does not require the use of if statements is using another dictionary for role entries.

# define roles dict
roles_dict = {"A": "Professor", "B":"Student"}

# get user data
userData= dict() 
userData["name"]=input("Insert your name and last name: ") 
role_letter=input("What is your role? \nA) Professor \nB) Student [A/B]: ")

# update dict
userData.update({"role": roles_dict[role_letter]})
print(userData)

Prints:

Insert your name and last name: Jayson

What is your role? 
A)Professor 
B) Student [A/B]: A
{'name': 'Jayson', 'role': 'Professor'}

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