r/PythonProjects2 • • 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

  1. 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.

  2. 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)

  3. 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​.

  4. 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.

  5. Create a ​main​ function to run your functions and print the total price.

0 Upvotes

12 comments sorted by

4

u/Meorge Apr 12 '20

What have you accomplished/understood of this assignment so far? I'm happy to try to help with clearing up misunderstandings and confusion, but I don't want to simply give answers.

2

u/gobionreddit Apr 12 '20

I am able to ask the user how much fruit they want by saying:

user_fruit = int(input(“How many pounds of bananas would you like?”)) User_fruit2 = int(input(“how many pounds of apples would you like?”)) User_fruit3 = int(input(“how many pounds of grapes would you like?”))

but am unsure how to return the response as a dictionary

2

u/Meorge Apr 12 '20

Once you've created the dictionary, you can return it just as you'd return any other variable:

# returns a dictionary containing two key-value pairs:
#   name = Meorge
#   favorite_food = pizza
def return_info():
    # create and populate the dictionary
    my_info = {"name": "Meorge", "favorite_food": "pizza"}
    return my_info

As for creating the dictionary itself: it's important to note that you can use variable names in place of values. So the following function would be just as valid:

def return_info():
    # these are the values of the dictionary
    my_name = "Meorge"
    my_favorite_food = "pizza"

    # create and populate the dictionary using variable values
    my_info = {"name": my_name, "favorite_food": my_favorite_food}

    return my_info

You could also write the function this way:

def return_info():
    # these are the values of the dictionary
    my_name = "Meorge"
    my_favorite_food = "pizza"

    # creating a new dictionary
    my_info = {}

    # assigning the key-value pairs of the dictionary
    my_info["name"] = my_name
    my_info["favorite_food"] = my_favorite_food

    return my_info

Finally, note that the keys of the dictionary ("name" and "favorite_food") are also values - and because of this, you can use variable names in their place too!

def return_info():
    # these are the keys of the dictionary
    name_key = "name"
    fav_food_key = "favorite_food"

    # these are the values of the dictionary
    my_name = "Meorge"
    my_favorite_food = "pizza"

    # creating a new dictionary
    my_info = {}

    # assigning the key-value pairs of the dictionary
    my_info[name_key] = my_name
    my_info[fav_food_key] = my_favorite_food

    return my_info

In your case, it sounds like you need to create a new dictionary and then populate it by having lines similar to my_info[name_key] = my_name - except instead of name_key it should be the fruit type, and instead of my_name it should be the number of pounds of that fruit the customer wants.

1

u/gobionreddit Apr 12 '20

Thank you for the examples. It really helped me to understand the concept! I am also not understanding the fourth part of the assignment.

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 typing dictionary["key"] by itself.

Here's a little example to illustrate this:

# asking the user for info
your_name = input("Enter your name: ")
your_age = int(input("Enter your age: ")

# creating a new dictionary and adding the user-submitted info to it
your_info = {}
your_info["name"] = your_name
your_info["age"] = your_age

# using information from the dictionary (important part!)
print("It sounds like your name is " + your_info["name"] + ", and in 10 years, your age will be " + str(your_info["age"] + 10))

Output from this program might look like:

Enter your name: Bob
Enter your age: 22
It sounds like your name is Bob, and in 10 years, your age will be 32

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 as price_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 function groceries(fruit_list))

Now, for each fruit, you just need to multiply the price per pound by the number of pounds the customer wants.

1

u/gobionreddit Apr 12 '20

This is my code right now. It has some issues and I am unsure how to fix them.

#part 1

fruits_list = ['bananas', 'apples', 'grapes'] #list with fruit keys

fruits_price = [0.59, 3.99, 2.99] #list with fruit values

#part 2

price_per_pound = {} #setting up dictionary for the 'for' loop

#sets each value from fruit list = to that of fruit price

for eachfruit in fruits_list and fruits_price:

price_per_pound[eachfruit] = fruits_price

#^fruit is the key and it is equal to fruits_price which is the value

#part 3

#asks user for amount of lb for each fruit, then returns user values in the dictionary fruit_quantity

def groceries(fruits_list):

bananas = int(input("How many bananas would you like?"))

apples = int(input("How many apples would you like?"))

grapes = int(input("How many grapes would you like?"))

fruit_quantity = {'bananas': bananas, 'apples': apples, 'grapes': grapes}

return fruit_quantity

#part4

def calculate_bill(dict_price, dict_quantity):

#dictioanry for price per fruit

dict_price = {'bananas': 0.59, 'apples': 3.99, 'grapes': 2.99}

#dictionary for price per pound

dict_quantity = {'bananas': bananas, 'apples': apples, 'grapes': grapes}

#multiplying amount customer wants by price per lb (finding total price)

bill = bananas * dict_price['bananas'] + apples * dict_price['apples'] + grapes * dict_price[grapes]

return bill

#executing everything above

def main():

print("Welcome to the virtual grocery store!")

print(groceries(fruits_list))

print(calculate_bill(dict_price, dict_quantity))

main()

ERROR MESSAGE:

Welcome to the virtual grocery store!

How many bananas would you like?1

How many apples would you like?1

How many grapes would you like?1

{'bananas': 1, 'apples': 1, 'grapes': 1}

Traceback (most recent call last):

File "/Users/ /Desktop/Programming/_dict.py", line 42, in <module>

main()

File "/Users/ /Desktop/Programming/_dict.py", line 41, in main

print(calculate_bill(dict_price, dict_quantity))

NameError: name 'dict_price' is not defined

How can I resolve these errors?

1

u/Meorge Apr 12 '20

The issue here is that the variable dict_price is not defined in the scope of your overall program - you give it a value inside of the calculate_bill() function, but outside of that it has no meaning. You either need to remove it from your call to calculate_bill() (and the function’s list of arguments) or you need to define it in the scope of your main() function so that you can pass it the variable (and in this case, you could remove the line where you define it inside of calculate_bill()).

1

u/gobionreddit Apr 12 '20

When I move it to the main function it says that thee variable bananas are not defined

1

u/Meorge Apr 13 '20

Like with dict_price, the scope of the variable bananas is limited to the function you created it in (i.e. the groceries() function). The easiest way to get around this is to declare bananas a global variable by adding global bananas right under the function declaration for each function you use that variable in. This will make it so that all functions including this line will reference the same variable.

As a side note, when typing code in Reddit, having three backticks (like ```) before and after the code block (on their own lines) will make the code easier to read.

1

u/dr_crispin Apr 12 '20

Just an aside from someone who’s written a script or two (but only two, mind you), while things like user_fruit, user_fruit2 etc will do for now, it’s best to get in the habit of making your names more descriptive. So, instead of

user_fruit = int(input(“How many pounds of bananas would you like?”))

You’d end up with something like

bananas_weight_wanted = int(input(“How many pounds of bananas would you like?”))

Only then, well, better. bananas_desired, pounds_of_bananas, user_desired_amount_of_bananas, yellow_thingmajigs_in... okay, well maybe not that last one.

If you’re gonna use user_fruit, or user_variable, or whatnot it’s fine in a small script like this, but if you’re gonna write bigger scripts (and eventually, you will) you’re gonna be left scratching your head as to what on earth you were doing with those.

2

u/gobionreddit Apr 12 '20

I see what you mean. It helps when writing the code as the the variable name is more like an English word so it is easier to remember and use. Thanks for the tip!

1

u/cheyen0609 Apr 12 '20

So are you interating over fruit_list to prompt for fruit weight? Assign the value with the list item as key to the dictionary. You should then have a dictionary for the function to be able to return the dictionary as the last function statement.