Yougandhara
Yougandhara

Reputation: 329

Python - dictionary is not getting updated properly

I am trying to run this program of supermarket. However, the list of items is not getting updated properly.

stock = {
    "banana": 6,"apple": 0,"orange": 32,"pear": 15
}    
prices = {
    "banana": 4,"apple": 2,"orange": 1.5,"pear": 3
}

def compute_bill(food):
    total = 0
    for item in food:
        if stock[item] > 0:
            total += prices[item]
            stock[item] -= 1
    return total

print "\n"
print "     Welcome to Supermarket!"
print "List of grocery items :"
print("{:<5}{:<8}{:<9}{:<10}".format("Num","Item","  Cost","  In Stock"))
counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

print "Specify the number of items : "
number = int (raw_input ())
order = {}
for i in range(number):
    groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
    itemNo = int(raw_input("How many iteam %s ?" % groceryitem))
    order[groceryitem] = itemNo

total = compute_bill(order)
print "total",total

counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

This is below my input and the output that I am getting

                Welcome to Supermarket!
List of grocery items :
Num  Item      Cost     In Stock
1    orange    RS 1.50   32
2    pear      RS 3.00   15
3    banana    RS 4.00    6
4    apple     RS 2.00    0
Specify the number of items :
2
Please enter the name of product 1:banana
How many iteam banana ?4
Please enter the name of product 2:pear
How many iteam pear ?5

Num  Item      Cost     In Stock
1    orange    RS 1.50   32
2    pear      RS 3.00   14
3    banana    RS 4.00    5
4    apple     RS 2.00    0

Since, I have specified 4 banana and 5 pear, those no of items should have been minus from the stock list. Why are the values in the stock dictionary not getting updated.

Please help!

Upvotes: 1

Views: 114

Answers (1)

BrenBarn
BrenBarn

Reputation: 251598

They are getting updated, but they're only reduced by one because you wrote stock[item] -= 1. If you want to reduce the stock by the number of items bought, you need to change that to stock[item] -= food[item]. You might also want to do total += food[item]*prices[item] so that the "shopper" is correctly charged for the number of items purchased.

Upvotes: 1

Related Questions