Dynamic dictionary access - python

related to dictionary and i want to access info from supermarket dynamically and if i access
in sequence all thing perfectly printed but if i want random access on items like wanted to
access soap in store1 is in or not then else part printed that 'item is not there'.
#dictionary to access data
supermarket={'store1':{'name':'vik general store','items':[{'name':'park avenue',
'quantity':200},{'name':'nivea','quantity':100}, {'name':'soap','quantity':500}]}
,'store2':{'name':'lucky general store','items':[{'name':'salt','quantity':600},
{'name':'sugar','quantity':700},{'name':'oil', 'quantity':400}]}}
##taking user input to enter store
s=input('enter the store name:')
#if store 1 opted and then get data from supermarket
if s=='store1':
##every key in item will be considered in sequence
for key in supermarket['store1']['items']:
n=input('enter the product to find:')
if key['name']==n:
print('product detail is :',key['name'],'....',key['quantity'])
else:
print('item is not there')
#if store 2 opted and then get data from supermarket
elif s=='store2':
#every key in item will be considered in sequence
for key in supermarket['store2']['items']:
n=input('enter the product to find:')
if key['name']==n:
print('product detail is :',key['name'],'....',key['quantity'])
else:
print('item is not there')

Op wants random access instead of sequential access, so I replaced the array named items from op's code with a dictionary with key as the product name and value as the quantity.
Then in the nested if statement I check if the product is present using special __contains__() method which returns a bool representing the presence of product and print the result
#dictionary to access data
supermarket = {
'store1': {
'name':'vik general store',
'items': { 'park avenue':200, 'nivea':100, 'soap':500 }
},
'store2': {
'name':'lucky general store',
'items':{ 'salt':600, 'sugar':700, 'oil':400 }
}
}
##taking user input to enter store
s = input('enter the store name:')
#if store 1 opted and then get data from supermarket
if s == 'store1':
n=input('enter the product to find:')
if supermarket['store1']['items'].__contains__(n):
print('product detail is :',n,'....',supermarket['store1']['items'][n])
else:
print('item is not there')
#if store 2 opted and then get data from supermarket
elif s=='store2':
n=input('enter the product to find:')
if supermarket['store2']['items'].__contains__(n):
print('product detail is :',n,'....',supermarket['store1']['items'][n])
else:
print('item is not there')

Related

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'}

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.

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 check if key exists in a for loop in python using scrapy

I'm trying to see if a business name matches with a previous business name and if it does break the iteration, if not continue with the iteration.
The problem
It is ignoring the break and I still see duplicates.
run.py
def parse(self, response):
for business in response.css('div.info'):
business_names = business.css('span[itemprop="name"]::text').extract()
business_name = business.css('span[itemprop="name"]::text').extract()
if business_name in business_names:
break
else:
website = business.css('div.links a::attr(href)').extract_first()
phone_number = business.css('div.phones.phone.primary::text').extract()
yield {
'Business Name': business_names,
'Website': website,
'Phone Number': phone_number,
}
I think business_names and business_name both are of list type and if you simply apply in operator it will return FALSE always. so better to use extract_first or any other logic while searching business_name in business_names.
Check for existance using the in operator and have some value for item. Right now your code is checking to see if an element of business_name is equal tobusiness_name
for item in business_name:
if item == business_name:
break
To:
if 'somevaluehere' in business_names:
break

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