r/PythonProjects2 • u/gobionreddit • Apr 11 '20
PYTHON DICTIONARIES HW HELP!
Hi all hope you are doing well during this unusual time. I am taking programming I class and it has been hard to communicate with my professor during these times so I decided to turn to reddit and ask for some help as I am confused with dictionaries. This is my first assignment with dictionaries. Help is very greatly appreciated!! Thanks in advance
Create a list called fruits_list with the values ‘bananas’, ‘apples’, and ‘grapes’ and a list called fruits_price with the values 0.59, 3.99, and 2.99.
Using a for loop, create a dictionary price_per_pound containing the elements of fruits_list as keys with the corresponding values from fruits_price (so bananas cost $0.59 per pound, apples cost $3.99 per pound, and grapes cost $2.99 per pound)
Create a function groceries(fruits_list) that asks the user for the number of pounds of each fruit type in the input list fruits_list and returns the information in a dictionary called fruit_quantity.
Create a function calculate_bill(dict_price,dict_quantity)that takes two dictionaries dict_price and dict_quantity as input arguments and returns the total value of the bill.
Create a main function to run your functions and print the total price.
2
u/Meorge Apr 12 '20
Great, I'm glad I could help!
As for the fourth part of the assignment: just like we can assign a key-value pair to a dictionary by typing
dictionary["key"] = "value", we can also get the value from a dictionary, as long as we know the key, by typingdictionary["key"]by itself.Here's a little example to illustrate this:
Output from this program might look like:
The point here is that you can access the value of a dictionary's item just like a regular variable by putting the key in square brackets immediately after the dictionary variable's name.
For the function you need to write in step 4, you'll have two dictionaries:
dict_price, which will have keys that are the different types of fruits, and corresponding values that are the price per pound of each fruit (the same dictionary asprice_per_pound, which you created in step 2)dict_quantity, which will have keys that are also the different types of fruits, and corresponding values that are the number of pounds of that fruit that the customer wants (the same dictionary that is being returned from the functiongroceries(fruit_list))Now, for each fruit, you just need to multiply the price per pound by the number of pounds the customer wants.