简体   繁体   中英

function to sum total values in dictionary

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)

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)

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)

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)

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

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())

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM