Search code examples
pythonlistdictionarycumulative-sumkey-value-store

How to total up values from dictionary when creating a new list



Stock = {
    'apple': .40,
    'cheese': .90,
    'banana': .60,
    'pear': .60,
    'steak': 3.00,
    'salad': 1.00,
    'ketchup': 1.00,
    'wine': 5.00,
    'beer': 4.50,
}
shoplist = []

for key, value in Stock.items():
    print(key, value)

# def checkout():
#     answer = input('Would you like to checkout and see your total? Please type \'y\' or \'n\'.')
#     if answer == 'y':


while len(shoplist) < len(Stock):
    item = input('Pick an item, or press Enter to checkout: ')
    if item in ['',' ']:
        from time import sleep
        print('Calculating total...')
        sleep(3)
        print('Here are your items:', shoplist)
        print('The total comes to') #was going alright but idk how to total the values when i've moved to the list :(
        break
    elif item in Stock:
        shoplist.append(item)
        print('Thank you - Your item has been added.')
    else:
        print('Please choose and item that is in stock.')
    continue

Hi I've created some code which will let you choose items from Stock, and then when you go to checkout it will show you the items you have chosen and then the total of the values you have selected. Only issue is the values that the user selects goes into a new list but I am unsure how to go back and pull the values from Stock and create a sum of those in shoplist at the checkout. Have I made mistake creating a new list or am I missing a method for doing such a thing? Thank you.


Solution

  • As Axe319 commented, the solution would be total = sum(Stock[i] for i in shoplist)

    Thank you