如何将列表中的值引用到字典键值?

时间:2018-11-03 03:35:19

标签: python python-2.7

因此,对于此代码,我有两个参数:一个是字典,里面装满了带有附加价格的杂货商品,另一个是商品本身。我的目标是添加放入购物车中的每件商品的价格。

例如,如果列表shopping_list定义为 ["shampoo", "brush", "shampoo", "soap", "soap", "dog food", "soap"],然后将这些对应的值相加。参数中已经为我定义了价格。但是,我对此非常执着。这是我到目前为止的内容:

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

我要返回的数字太高了。

2 个答案:

答案 0 :(得分:0)

这将从对应于列表中项的字典中取出值,并求和:

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

答案 1 :(得分:0)

如果商品中不存在商品=>我将其设置为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