简体   繁体   中英

Compare dict value with other dict

I have an dict which contains treshold value and a dict with some acutal amounts. Which not always contain all keys from the minimum treshold dict.

Now i would like to compare the actualAmounts with the minimumTresholds, this is what i come up with, but that does not work

minimumTresholds = {'key 1' : 100, 'key 2' : 100, 'key 3' : 1000}
actualAmounts = {'key 1' : 237, 'key 3' : 903}

for k, v in actualAmounts.items():
    if actualAmounts[k] == minimumTresholds[k] and actualAmounts[v] < minimumTresholds[v]:
         print(actualAmounts[k])

The expected result would be:

'key 3'

Any thoughts?

This should work:

minimumTresholds = {'key 1' : 100, 'key 2' : 100, 'key 3' : 1000}
actualAmounts = {'key 1' : 237, 'key 3' : 903}

for i in actualAmounts.keys() :
    if i in minimumTresholds.keys() and actualAmounts[i] < minimumTresholds[i] :
        print(i)
    

There is problem in your logic.

if actualAmounts[k] == minimumTresholds[k] and actualAmounts[v] < minimumTresholds[v]: You are doing a lookup in a dict with a value. actualAmounts[v] will trow an error since the value is not a key in that dict.

you can check if the key is present in the the other dict using the in keyword:

for key, value in actualAmounts.items():
    if key in minimumTresholds and value < minimumTresholds[key]:
        print(key)

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