Python比较两个键/值对

时间:2013-11-03 14:32:11

标签: python list key-value

我有两组键值对,如下所示:

tom = {'coffee': 2, 'hotdog': 1}

和另一个像这样:

namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}

我想比较与'tom'关联的键与'namcat'中的值相同时的比较,如果是,则为运行总计添加1。我认为它使用导致我问题的列表迭代键值对。

1 个答案:

答案 0 :(得分:2)

for k, v in namcat.items():
    for item in v:
        for key, value in tom.items():
            if value == item:
                running_total += 1

演示:

>>> hotdog = 1
>>> coffee = 2
>>> foodstand = 6
>>> breakfast = 10
>>> tom = {'coffee': 2, 'hotdog': 1}
>>> namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
>>> running_total = 0
>>> for k, v in namcat.items():
    for item in v:
        for key, value in tom.items():
            if value == item:
                running_total += 1


>>> running_total
2

这应该这样做。希望它有所帮助!