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,
})
Related
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'}
I've created a function : A dictionary which takes in city name and country name to which the city belongs to. Currently the code just returns a dictionary after each iteration with city name and country name after taking inputs using the input(). I'm trying to update the code (no success so far) so that a new dictionary is printed after each iteration with updated dictionary which returns an output like
{'city' : 'berlin', 'country' : 'germany',
'city' : 'paris', 'country' : 'france',}
The code is as follows :
def city_country(city_name, country_name):
pair = {'City': city_name, 'Country': country_name}
return pair
active = True
while active:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
new_pair = city_country(user_city, user_country)
print(new_pair)
The keys of the dictionary type are unique, this way of writing you can always print only one city and one country, maybe you can try to do it in json format, but it means you have to write another function to deal with the duplication of data (directly add or replace)
def city_country(city_name, country_name):
return {'City': city_name, 'Country': country_name}
data = []
while True:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
data.append(city_country(user_city, user_country))
print(data)
city_country_dict = {}
active = True
while active:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
new_pair = city_country(user_city, user_country)
#=================================
city_country_dict.update(new_pair)
#=================================
print(city_country_dict)
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')
I'm webscraping wellrx.com. I'm trying to create a dictionary for each page that I scrape and adding that page to an csv file.
I am getting the name and price on one page, clicking a link to get to the alternative drug name/price and getting the name and price for that page.
Ex: Dictionaries should be
{'drug name': 'ARIPIPRAZOLE', 'price': '$16.45', 'other name': 'ABILIFY', 'price1': '$892.59'}
{'drug name': 'PIOGLITAZONE HCL', 'price': '$9.00', 'other name': 'ACTOS', 'price1': '$392.11'}
but I just get
{'drug name': 'PIOGLITAZONE HCL', 'price': '$9.00', 'other name': 'ACTOS', 'price1': '$392.11'}
#get drug name and price
pages_dict = {}
try:
drug_name = driver.find_element_by_xpath('//h4[#class="displayName skel skel-displayName"]').text
price = driver.find_element_by_xpath('//p[#class="right pr2"]').text
pages_dict['drug name'] = drug_name
pages_dict['price'] = price
print(pages_dict)
except:
continue
#click the alternative name
try:
name = driver.find_element_by_xpath('//h5[#id="OtherName"]').text
name1 = re.findall(": (.*)", name)[0]
driver.find_element_by_link_text(name1).click()
time.sleep(5)
#other drug name
other_name = driver.find_element_by_xpath('//h4[#class="displayName skel skel-displayName"]').text
price1 = driver.find_element_by_xpath('//p[#class="right pr2"]').text
pages_dict['other name'] = other_name
pages_dict['price1'] = price1
print(pages_dict)
except:
continue
I think you have first to learn about dictionaries, because you are always overwriting the same key with:
pages_dict['drug name'] = drug_name
pages_dict['price'] = price
just try:
pages_dict[drug_name] = drug_name
pages_dict[price] = price
and you will see how different keys are store with different values.
If you wish to store the price for every drug it would be more reasonable to do something like this:
pages_dict[drug_name] = price
If you instead want the same kind of dict with fixed keys representing one instance I suggest you to create a list of dictionaries:
list_of_dicts = []
pages_dict = {}
# Put a block code who creates page_dict
list_of dicts.append(pages_dict)
# Put a block code who creates page_dict
list_of dicts.append(pages_dict)
# Put a block code who creates page_dict
list_of dicts.append(pages_dict)
for pages in list_of_dicts:
print(pages)
But this is obvious not a nice way to implement. You should use some iteration (for or while) through the pages. The code you posted needs a lot of revision. It's quite unreadable.
I intend to save a contact list with name and phone number in a .csv file from user input through a dictionary.
The problem is that only the name is saved on the .csv file and the number is omitted.
contacts={}
def phone_book():
running=True
while running:
command=input('A(dd D)elete L)ook up Q)uit: ')
if command=='A' or command=='a':
name=input('Enter new name: ')
print('Enter new number for', name, end=':' )
number=input()
contacts[name]=number
elif command=='D' or command=='d':
name= input('Enter the name to delete: ')
del contacts[name]
elif command=='L' or command=='l':
name= input('Enter name to search: ')
if name in contacts:
print(name, contacts[name])
else:
print("The name is not in the phone book, use A or a to save")
elif command=='Q' or command=='q':
running= False
elif command =='list':
for k,v in contacts.items():
print(k,v)
else:
print(command, 'is not a valid command')
def contact_saver():
import csv
global name
csv_columns=['Name', 'Phone number']
r=[contacts]
with open(r'C:\Users\Rigelsolutions\Documents\numbersaver.csv', 'w') as f:
dict_writer=csv.writer(f)
dict_writer.writerow(csv_columns)
for data in r:
dict_writer.writerow(data)
phone_book()
contact_saver()
as I am reading your code contacts will look like
{
'name1': '1',
'name2': '2'
}
keys are the names and the value is the number.
but when you did r = [contacts] and iterating over r for data in r that will mess up I guess your code since you are passing dictionary value to writerow instead of a list [name, number]
You can do two things here. parse properly the contacts by:
for k, v in contacts.items():
dict_writer.writerow([k, v])
Or properly construct the contacts into a list with dictionaries inside
[{
'name': 'name1',
'number': 1
}]
so you can create DictWriter
fieldnames = ['name', 'number']
writer = csv.DictWriter(f, fieldnames=fieldnames)
...
# then you can insert by
for contact in contacts:
writer.writerow(contact) # which should look like writer.writerow({'name': 'name1', 'number': 1})