Home > Back-end >  Compare dict value with other dict
Compare dict value with other dict

Time:02-23

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?

CodePudding user response:

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)

CodePudding user response:

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)
    
  • Related