My goal for this function is for it to output the grand total cost for an order.
I have one function that gives me a dictionary like {'2': '150.99', '3': '99.50', '15': '5.07'} where the first value is an ID number and the second value is the price for the item with that ID number. So item number 3 costs 99 Dollars/Euros/Pounds/Whatever my units are and 50 cents/subunits.
Another function gives me a list of item IDs to look up like this [2, 2, 3] where any item ID can appear more than once to show that I am purchasing more than one of that item. So in this example I’d be buying 2 of item 2 at 150.99 each and 1 of item 3 at 99.50.
I want to define a function that lets me pass it the dictionary of item ID: prices and the list of item IDs to lookup and it would output the total cost for all items in the list. So for the above example it should output the value 401.48 because (2*150.99)+99.50=401.48.
As a test I have tried
test = DictionaryVariable.get('2')
print test
This prints the expected value (so in this example it’d be 150.99.)
However, my attempts to define a function like
def FindPrice(dictionary, idlist):
price = 0.00
for id in idlist:
price + float(dictionary.get(id))
return price
and then call it like this:
Prices = FindPrice(DictionaryVariable, IDListVariable)
print Prices
have not worked – the dictionary.get(id) part seems to be returning None (which I have tested by making it a str instead of float) so it throws an error saying “TypeError: float() argument must be a string or a number”. I suspect that I need to use some other method of feeding in the item IDs from my list, but I don’t know what that method would be. I am not sure why the dictionary.get(id) returns None but yet DictionaryVariable.get('2') gives it the value I’d expect.
EDIT:
Thanks to the helpful posts that pointed out that I was using strings in my dictionary rather than integers or floats I got this to work:
def FindPrice(dictionary, idlist):
Price = sum(float(dictionary.get(x,0)) for x in idlist)
return Price
Prices = FindPrice(DictionaryVariable, FunctionThatMakesListofIDs('FileToGetIDsFrom.xml'))
print Prices
Your list [2, 2, 3] contains integers, but the keys of your dict are strings. I propose you create your dict using int keys and float values to begin with, or convert it like this: