Reputation: 311
I have a dict with several entries for the value.
inventory = {847502: ['APPLES 1LB', 2, 50], 847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],
483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50], 485034: ['BELL PEPPERS 1LB', 3, 50]}
I want to create a function to get the total of the value items ie. sum((2*50)+ (1*100) etc...) I think I'm nearly there but this seems to only add the first value....
def total_and_number(dict):
for values in dict.values():
#print(values[1]*values[2])
total =0
total += (values[1]* values[2])
return(total)
total_and_number(inventory)
Upvotes: 0
Views: 566
Reputation: 4664
Try this:
x = {
847502: ['APPLES 1LB', 2, 50], 847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],
483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50], 485034: ['BELL PEPPERS 1LB', 3, 50]
}
print(sum([x[i][1]*x[i][2] for i in x.keys()]))
output :
C:\Users\Desktop>py x.py
650
EDIT : For your own code you need to take out total=0
and return total
from the loop.
def total_and_number(dict):
total = 0
for values in dict.values():
total += (values[1]*values[2])
return(total)
print(total_and_number(x))
Output :
C:\Users\Desktop>py x.py
650
Upvotes: 1
Reputation: 580
You should try and access the items through their key values:
def total_and_number(dictis):
total = 0
for key in list(dictis.keys()):
print(key)
total += (dictis[key][1]*dictis[key][2])
return(total)
It does return the expected value you need.
Upvotes: 0
Reputation: 54223
Looks like every value is a list (though it should probably be a tuple) of:
itemname, qty, eachprice
So it should be easy enough to iterate through and sum directly:
sum(qty*eachprice for _, qty, eachprice in inventory.values())
Upvotes: 1
Reputation: 2564
Return and total rows were misplaced. This returns 650.
inventory = {847502: ['APPLES 1LB', 2, 50],
847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],
483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50],
485034: ['BELL PEPPERS 1LB', 3, 50]
}
def total_and_number(dict):
total = 0
for values in dict.values():
total += values[1]*values[2]
return(total)
total_and_number(inventory)
Upvotes: 2
Reputation: 1280
Use:
def total_and_number(d):
tot = 0
for k, v in d.items():
tot += v[1]*v[2]
return tot
total_and_number(inventory)
Upvotes: 1
Reputation: 318
You should define variable total out of for loop codes.
result = sum([ value[1]*value[2] for value in inventory.values()]
or
def total_and_number(dict):
total =0
for values in dict.values():
#print(values[1]*values[2])
total += (values[1]* values[2])
return total
total_and_number(inventory)
Upvotes: 1