Skip to content
Advertisement

looping through dictionary and printing first value where condition is met

Having some trouble getting this simple conditional to work. I have a dictionary with 10 key-value pairs as follows:

{0.1: 0.91, 0.2: 0.701, 0.3: 0.522, 0.4: 0.203, 0.5: 0.042, 0.6: 0.004, 0.7: 0.0, 0.8: 0.0, 0.9: 0.0, 1.0: 0.0}

I’m trying to loop through the dictionary and print the key for the first value that is below 0.05.

This is the code I have right now:

i = 0
length = len(list(adf_dict.items()))
keys, values = list(adf_dict.keys()), list(adf_dict.values())

    while i < length:
        if values[i] < 0.05:
          print(key[i])
        else:
          break

Can anyone help me see where I’m going wrong here?

Edit: It should be noted that I only want to print the first key where the condition is met and then end the loop.

Advertisement

Answer

This is what your looking for:

for key, value in adf_dict.items():
    if value < 0.05:
        print(key)
        break
Advertisement