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.
CodePudding user response:
Possible solution is the following:
userData= {}
userData["name"]=input("Insert your name and last name: ")
role=input("What is your role? \nA) Professor \nB) Student \n[A/B]: ")
if role == 'A':
userData["role"] = "Professor"
elif role == 'B':
userData["role"] = "Student"
else:
print("Please enter correct role")
userData= {}
print(userData)
Prints
Insert your name and last name: Gray
What is your role?
A) Professor
B) Student
[A/B]: B
{'name': 'Gray', 'role': 'Student'}
CodePudding user response:
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'}