My calculation takes forever when the duration is supposed to be short (0.2 second). when i interrupt the cell, it allows to finish the process at 100%.
Context :
I want to verify that a value is in a dictionnary, for that I iterate on the dictionary :
i = 0
j = 0
while i < 9 :
try :
if dictionary[i] == "my_value" :
j = i
break
except :
i =1
Where j
is here to store the location of the key in the dictionary.
What happens is that it should take 0.2 seconds to process. However, it runs infinitely. If I interrupt the cell, two scenarios happen :
- The interruption goes as expected
- The interruption actually completes the operation and displays the result
Example : I print i
at each step and I get :
Running forever, frozen on a random number
>>>0
>>>1
>>>2
>>>3
>>>4
>>>5
>>>6
>>>7
Then, when I interrupt the cell, I get :
>>>0
>>>1
>>>2
>>>3
>>>4
>>>5
>>>6
>>>7
>>>8
>>>9
>>>j = 2
aka the run of the cell is successful, I get the output that I expected. In conclusion, interrupting the cell allows the operation to be successful.
I do not understand what happens exactly, maybe the interruption exists a try()
that was stuck.
The problem is that it is obviously not consistent at all to manually interrupt the cells (sometimes it really interrupts the cell without finishing the computation).
What causes the infinite run? How to fix the code? Thank you in advance.
CodePudding user response:
The while
loop is always checking the if
condition, but because i=0
is not going to change, the condition is always false and you are stuck in the loop forever
Try to add i = 1
in the try
block so that it will not stuck at i=0
, like this:
dictionary = {1:'', 2:'', 3:'', 4:'', 99:'', 6:'my_value', 7:'', 8:'', 9:'', }
i = 0
j = 0
while i < 9 :
try :
if dictionary[i] == "my_value" :
print(i, dictionary[i])
break
else:
print(i)
i =1
except :
print('exception at', i)
i =1
Output
exception at 0
1
2
3
4
exception at 5
6 my_value
CodePudding user response:
Value in dictionary
To know if a value is in a dictionary use:
is_in = "your_value" in your_dict.values()
Key of your value
The previous function only tells if a value is in a dictionary but not the key to that value. To know the key you can do a loop:
your_key = ""
for key, value in your_dict.items():
if value == "your_value":
your_key = key
break
Also you can use lists to find the key:
list(your_dict.keys())[list(your_dict.values()).index("your_value")]
My recomendation is to always search for a build in function before writing a loop. Most of the times there is one that does the job ;)
Infinite loop
Note that you only increment the variable i
if an exception happens.
No exception -> No increment of i
-> No exception