Casa > H > How To Fix “Keyerror: 0” Python With A Dictionary

How to fix “KeyError: 0” Python with a dictionary

Thanks for A2A, KeyError in Python dictionary means we tried to access key ‘0’ value from the dictionary where the key isn’t present in that dictionary (or) which isn’t initialized.

We can fix this error by following the below methods:

METHOD I-

Try to check whether the key is present in the dictionary before using it to access the dictionary value.

You can check this by using the “in” operator.

Eg:

  1. d={1:3,3:6} 
  2. for i in range(1,5): 
  3. if i in d: 
  4. print(d[i]) # or any other operation you would like to perform. 

Output-

3

6

As here we tried to access the keys within a range of 1–5 where 2,4 are not a part of the keys in a dictionary it didn’t throw an error and we are able to proceed with our program.

- - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - - - - - - -

METHOD II-

We can use a try-except block to get rid of the key error.

Eg:

  1. d={1:3,3:6} 
  2. for i in range(1,5): 
  3. try: 
  4. print(d[i]) 
  5. except KeyError: 
  6. continue 

Output-

3

6

“continue” helps us to perform the ‘for’ loop on getting the key error.

——————————————

If we place the try block out of the for loop we could catch the error but the program flow stops

Eg:

  1. d={1:3,3:6} 
  2. try: 
  3. for i in range(1,5): 
  4. print(d[i]) 
  5. except KeyError: 
  6. print("ERROR") 

Output-

3

ERROR

As we can see on accessing the key ‘2’ which isn’t present in dictionary error is caught but the program is terminated.

Hope I made it clear :)

De Lamp

Como podemos esconder dados JSON de ferramentas como ferramentas de desenvolvimento Chrome e Firebug, etc., como uma segurança além de 'https'? :: O que você acha de acampar no PUBG mobile?