Hi I have a doubt in calling a function with string name as it is showing error: LIST INDICES MUST BE AN INTEGER
I agree with the error statement but don't have the clue what to do. As when I am giving function argument parameter as a Dictionary , (option 2), its function is accepting it and running the code smoothly. But on giving it just the name of the key (as a I did in option 1), it is showing Indices error because I am accessing key which is a string not integer & it doesn't have the key with value (which is an error of unhashable key). So,
Please explain me following:
How to create a dictionary with key name but empty value. How to compare whether it is a list name is given in arguments of the function or a dictionary key. Please suggest code. Solution of my code. FOR OPTION 1
Code:
# CODE FOR DETRMINING PRICE AS PER STOCK
#PYTHON 2.7 SCRIPT
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_bill(food):
x = 0
total1 = 0
total2 = 0
z=0
for key in food: # I KNOW I AM DOING ERROR HERE, BUT NO CLUE WHAT TO DO!!
count = stock[key] #INTIAL COUNT
print "this is the stock of %s : %d " % (key,count)
count = stock[key] - food[key] # STOCK REMAINING
print "this is the stock remaining of %s : %d " % (key,count)
if count > 0: # CHECKING WHETHER IT IS IN STOCK OR NOT
z = prices[key] * food[key] # FINDING TOTAL
total1 = z + total1 # ACCUMLATING TOTAL
print "this is the total1 of %s : %f \n" % (key,z)
elif count <= 0: # OVER-STOCK OR EMPTY STOCK
z = prices[key] * stock[key]
total2 = z + total2
print "this is the total2 of %s : %f \n" % (key,z)
x = total1 + total2 #COMPUTING WHOLE TOTAL
print "\n this is the whole total : %f \n" % x
return x
# JST WANT ALL PEAR
compute_bill(['pear']) #OPTION 1: NOT WORKING!! NEED SOLUTION
#OPTION 2 : WORKING :
order = {'apple' : 1, 'banana' : 3, 'pear' : 3, 'orange' : 3}
compute_bill(order)
Advance Thanks & Cheers!!
You need to check whether the passed in object is a dictionary (an order
) or a list (an item
) ... You also need to decide exactly what behavior you want in the second case, but let me guess you want to answer with the total price for the available stock:
def compute_bill(food):
if isinstance(food, dict):
compute_bill_for_order(food)
if isinstance(food, list):
compute_bill_for_items(food)
def compute_bill_for_order(order):
for key in order.keys(): ## You also have to call the `keys` method
# Here goes the exact same code you have for the cases
# count > 0 and count <= 0
# Basically, the `compute_bill` method
pass
def compute_bill_for_items(items):
total = 0
for item in items:
total += prices[item] * stock[item]
return total