Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Error 4 in Python

I keep getting this error whenever I delete part of a dictionary in python. Early on I have

del the_dict[1]

and then later when I run through the dictionary I immediately get the error

test_self = the_dict[element_x]

KeyError: 4

Does anyone have any idea what that error is. Everything is properly deleted from the dictionary, but when I go back to search through it, I get this error.

like image 363
ben Avatar asked Nov 24 '12 18:11

ben


1 Answers

It seems that you are by mistake trying to access the dictionary element on index. You can't do that. You need to access dict value on key. As dictionary is not ordered.

E.g :-

>>> my_dict = {1:2, 3:4}
>>> my_dict
{1: 2, 3: 4}
>>> 
>>> del my_dict[0]  # try to delete `key: 1`

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    del my_dict[0]
KeyError: 0
>>> del my_dict[1]  # Access by key value.
>>> my_dict   # dict after deleting key 
{3: 4}
>>> my_dict[1]   # Trying to access deleted key.

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    my_dict[1]
KeyError: 1

Everything is properly deleted from the dictionary, but when I go back to search through it

You of course cannot get the value of key, that you have deleted. That will give you KeyError. Why would you want to do something like that? I mean, why you want to access the thing, which you know does not exist?

Alternatively, you can use in operator to check for the existence of a key in your dictionary: -

>>> my_dict = {1:2 , 3:4}
>>> 4 in my_dict
False
>>> 1 in my_dict
True
like image 170
Rohit Jain Avatar answered Oct 05 '22 20:10

Rohit Jain