1

Ive got two sets of key value pairs that look like this:

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

and another like this:

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

Id like to compare whenever a key associated with 'tom' is the same as a value in 'namcat', and if so add 1 to a running total. I think its iterating over key-value pairs with lists that is causing me issues.

4

1 回答 1

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

这应该这样做。希望能帮助到你!

于 2013-11-03T14:35:50.973 回答