简体   繁体   中英

Python Compare Two Key/Value Pairs

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.

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

Demo:

>>> 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

This should do it. Hope it helps!

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