简体   繁体   中英

How can I reference a value from a list to the dictionary key value?

So I have two arguments for this code: one is a dictionary full of grocery items with attached prices, and one is the items themselves. My goal is to add the prices of each item I put in my grocery cart.

For example, if the list shopping_list is defined as ["shampoo", "brush", "shampoo", "soap", "soap", "dog food", "soap"] , then I would add those corresponding values together.The prices are already defined in the argument for me. However, I am extremely stuck on this. This is what I have so far:

def shopping(products, shopping_list):
    total = 0
    for n in shopping_list:
        if n in products.keys():
            total += sum(products.values())
    return total

the numbers I'm returning are way too high.

This takes value out of dictionary corresponding to item in list and takes the sum:

lst = ["shampoo", "brush", "shampoo", "soap", "soap", "dog food", "soap"]

d = {'shampoo': 2, 'brush': 1, 'soap': 3, 'dog food': 5}

print(sum(d[x] for x in lst))
# 19

对于产品中不存在案例项目 => 我将其设置为 0。

shopping_list = ["shampoo", "brush", "shampoo", "soap", "soap", "dog food", "soap"] products = {'shampoo': 2, 'brush': 1, 'soap': 3, 'dog food': 5} final_result = {} for item in shopping_list: if item in final_result: final_result[item] += products.get(item,0) else: final_result[item] = products.get(item,0) return final_result

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