Creating a dictionary with multiple user input choices in python - 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'}

Related

Grab a User ID from a dict (Discord.py)

I've been getting the hang of Discord.py lately. Managing dictionaries, bot arguments, all that jazz. To finish off point management in my bot, I want to make a leaderboard. Following this answer, i structured my code slightly differently from them.
#bot.command(pass_context=True)
async def testboard(ctx, top:int=10):
total=[]
total = sorted(total,reverse=True)
board=discord.Embed(title = f'Top {top} highest awarded monkes.')
index = 1
if index == top:
return
else:
index += 1
for str in points:
userid = points[str]
user= bot.get_user(userid)
if index==1:
badge="\U0001F947"
elif index==2:
badge="\U0001F948"
elif index==3:
badge="\U0001F949"
else:
badge="\U0001F539"
board.add_field(name=f"**{badge}{index}. {user}**",value=(f"{points[str]} points"), inline=False)
await ctx.send(embed=board)
While it does display the points stored in my database, it doesn't do it from greatest to least, and doesn't display the name of the user.
As seen here: Result
I suspect it's because how my dictionary is structured.
{"userid": 0, "userid": 8, "userid": 0, "userid": 35, "userid": 11, "userid": 6}
Perhaps I can grab the name of the variable? If so, how can I do that?
The reason the username is just showing up as "None" is this portion of the code:
userid = points[str]
user= bot.get_user(userid)
If the str variable from the for loop is the user id, then the userid variable you are creating here is the point score for that user, not the id itself, so bot.get_user returns None because it won't find a user with, for example, an ID of 0. Change those lines to the following:
user= bot.get_user(int(str))
Secondly, the points are not in order because dictionaries are not ordered at all, so you would have to sort the objects manually. One way to do that is to get the entries of the dictionary, including both the key (the userid) and the value (number of points), sort it by points, and then iterate through it in a for loop:
for (userid, score) in sorted(points.items(), key=lambda entry: entry[1], reverse=True):
user= bot.get_user(int(userid))
if index==1:
badge="\U0001F947"
elif index==2:
badge="\U0001F948"
elif index==3:
badge="\U0001F949"
else:
badge="\U0001F539"
board.add_field(name=f"**{badge}{index}. {user}**",value=(f"{score} points"), inline=False)
I changed a couple of variable names here, most importantly str which is the class name for the string type, so it could potentially cause conflicts. Also, per your comment, the get_user method seems to require an integer and won't do conversion automatically.

How to get value from dict if its key can have several values

I have a dict with credentials like the following:
secret = {"password": "jdksal",
"user": "fjdklas",
"schema": "jfdaskl"}
I want to create a variable for password, user and schema. However, the secret dict can have other values for each key, so that I would have a list of possibles ways of naming the elements, like the following:
pass_words = ['password', 'pass', 'contraseƱa']
Thus, the variable password would be created when any key of the list pass_words exists in the dictionary. Only one word from pass_words would be present in the dict. Same with user, schema etc. So far I have this code:
for word in pass_words:
if word in secret:
password = secret[word]
user_words = ['user', 'username', 'login', 'name']
for word in user_words:
if word in secret:
user = secret[word]
It works, but its very verbose. Is there any less verbose way to do it? Thanks
As you have written it, password will get the last match if there is more than one overlap between pass_word and secret. I don't know is that is your intent.
You could use set operations if there is only one overlap:
>>> secret.keys() & pass_words
{'password'}
>>> secret.keys() & user_words
{'user'}
Then to get the value associated with that key:
>>> secret[(secret.keys() & pass_words).pop()]
jdksal
>>> secret[(secret.keys() & user_words).pop()]
fjdklas
For older Pythons that don't have dict set views, just apply set to each for the same result:
>>> set(secret.keys()) & set(user_words)
{'user'}
With Python 3.6+, you can do:
password, user={k:v for k,v in secret.items() if k in pass_words+user_words}.values()
I Think This Will Be Better:
pass_words = ['password', 'pass', 'contraseƱa']
secret = {"password": pass_words,
"user": "fjdklas",
"schema": "jfdaskl"}
input_password = input("Enter Your Password: ")
for key,value in secret.items():
if input_password in value:
print("Correct Password")
You Can Change The Input Method As You Like. The Key Variable Will Hold The Key Of The First Item In The Dictionary And The Value Variable Will Hold The Value, Which Will Be A List In Your Case, For The First Item In The Dictionary.

Dictionary Getting Overwritten in While Loop

def get_list_expenses():
expense_list = {}
print('Please type the name of the expense followed by the price of the expense')
while True:
name = input('Name of expense: ')
price = int(input('Price of expense: '))
expense_list.update({
'name': name,
'price': price,
})
cont = input('Want to add another? [y/n] ').lower()
if cont == 'n':
break
print(type(expense_list))
print(expense_list)
return expense_list
Input ==========================
Please type the name of the expense followed by the price of the expense
Name of expense: Food
Price of expense: 100
Want to add another? [y/n] y
Name of expense: Car Insurance
Price of expense: 200
Want to add another? [y/n] n
Output =========================
<class 'dict'>
{'name': 'car', 'price': 200}
I'm new to python and wanted to try and make a budget application to save me time manually inputting information to excel. My idea was to create a loop that would take in the name of an expense and the price per month of it. I wanted to put this into a dictionary so I could .get the information whenever I needed it. However, my dictionary keeps getting overwritten. I've tried a few different solutions I can find online but nothing worked. Thanks in advance.
Using the update method on a dictionary you are basically rewriting the dictionary from scratch at every iteration, for this reason you see a single value at the end (the last one).
I would suggest to create an empty list and then append a new dictionary of values at every iteration:
def get_list_expenses():
expense_list = []
print('Please type the name of the expense followed by the price of the expense')
while True:
name = input('Name of expense: ')
price = int(input('Price of expense: '))
expense_list.append({
'name': name,
'price': price,
})
cont = input('Want to add another? [y/n] ').lower()
if cont == 'n':
break
print(type(expense_list))
print(expense_list)
return expense_list
expense_list.update({
'name': name,
'price': price,
})
Should be:
expense_list.update({name,price})
Dictionary is a key value pair. In your case key will be 'Name of expense' and value will be price. The way you are creating you have 2 keys in dictionary. 1st key is 'name' and second key is 'price'.
You can simply do:
expense_list[name] = price
If name exists it will update otherwise will add.
Make expense_list an actual list:
expense_list = []
and then append to it
expense_list.append({
'name': name,
'price': price,
})

How to compare usernames in python (comparing lists with title case objects)?

I have the following code in Python 3.6.0. I am a newbie and have been trying to get this code to work. I don't know how to get python to recognize (and reject) if the user enters the same username with capitals letters; below is the code.
I would appreciate if you can show me how, please avoid comprehensions, just show me the full length code: (since "albert" is entered in new_user, I want the program to reject the user name since it is in the current_user in title letters.
current_user = ["John","Peter","sam","Albert"]
new_user = ["albert"]
for name in new_user:
if name.lower() in current_user:
print ("Sorry Username is taken, please enter a new username")
else:
print ("Username accepted")
This is a situation where comprehensions really shine - however if you want to do it the long way, one option is:
current_user = ["John","Peter","sam","Albert"]
new_user = ["albert", "george", "John", "FRED"]
for new in new_user:
name_ok = True
for current in current_user:
if new.lower() == current.lower():
print ("Sorry {} is taken, please enter a new username".format(new.lower()))
name_ok = False
break
if name_ok:
print ("Username {} accepted".format(new.lower()))

How can I store the users' data properly?

I am restoring data for users' in a nested dictionary as follows:
user_dict = {user_name:{product:amount, product:amount}}
So, user_name is the user's user_name. The product is the what the user put in the basket(e.g. orange juice), and the amount is the amount of a specific product. So, for instance:
user_dict = {"sara" : {"orange juice": 2, "apple juice" : 4}, "ali": {"banana":3}}
what I want to do is that when a user buys some stuff and put them in the (user_dict) then logs out, when the same user logs in again, I want to get the user's basket as follows: let's say sara logged in and put some stuff in her basket(user_dict) then logged out, when sara logs in again, I want to make get sara's information from the (user_dict) in a new dictionary(called basket) like this:
basket = {"orange juice": 2, "apple juice" : 4}
Also, I want to make the basket empty if the user (user_name) who logged in does not have anything in the basket. So, I want to make users' things do not interfere and I do not want to lose any information. I have almost finished my project but this is what I am stuck at, so help me guys, please.
Here are my lines of code for this task:(but the code does not work as I want)
for key in user_dict.keys():
if user_name == key:
key_sto = " "
nested_dict = user_dict[user_name]
val = a.values()
val_in_nested = val[0]
key_in_nested = key_sto.join(a)
basket[key_in_nested] = val_in_nested
elif user_name != key :
basket = {}
I was able to solve the problem, so here is the code.
for key, amount in user_dict.items():
if key == user_name:
basket = amount
if user_name not in user_dict.keys():
basket = {}

Categories

Resources