如何遍历字典中的键并匹配另一个字典中的键/值

时间:2021-02-10 17:41:47

标签: python arrays dictionary

我正在尝试构建一个程序,该程序将采用 [int,int] 或键/值对的嵌套列表,并与另一个字典的键/值进行匹配,并将第二个中的值添加到启动于的 int 变量中0.

awk '
    { vals[$2] = vals[$2] $0 ORS }
    END {
        for (i in vals) {
            if ( gsub(ORS,"&",vals[i]) == 3 ) {
                printf "%s", vals[i]
            }
        }
    }
' eq9_1.ndx

from collections import Counter shoe_sizes = [2,3,4,5,6,8,7,6,5,18] shoe_collection = Counter(shoe_sizes) customer_wants = [[6,55],[6,45], [6,55], [4,40], [18,60], [10, 50]] income = 0 for i in customer_wants: if i in shoe_collection: income += dict[customer_wants[i][1]] print(income) 中的键是鞋码,值是可用的数量。 我在这里要做的是获取 shoe_collection 中的每个嵌套列表,并检查 customer_wants 中的第一个元素(鞋码)是否可用。如果是这样,我想在 shoe_collection 中添加该嵌套列表的第二个元素(价格)并将其添加到 customer_wants。 使用两个字典而不是将 income 作为嵌套列表会更容易吗?我尝试比较 list-dict 和 dict-dict 但得到了两者都不可哈希的 TypeErrors。谢谢!

2 个答案:

答案 0 :(得分:1)

用这个替换你的 for 循环:

for size, price in customer_wants:
    if shoe_collection[size] > 0:
        shoe_collection[size] -= 1
        income += price

根据文档,Counter 对象为丢失的键返回 0 的原则是:

<块引用>

Counter 对象有一个字典接口,除了它们为丢失的项目返回零计数而不是引发 KeyError

因此不需要检查键是否存在,我们只需要检查该键是否具有正值。如果是,则将价值减少 1 并将价格添加到收入中。

答案 1 :(得分:0)

也许你可以这样说,

shoe_sizes = [2,3,4,5,6,8,7,6,5,18]

customer_wants = [{'size':6,'value':55},{'size':6,'value':45}, {'size':6,'value':55}, {'size':4,'value':40}, {'size':18,'value':60}, {'size':10, 'value':50}]
income = 0
for i in customer_wants:
    if i['size'] in shoe_sizes:
       income+=i['value']