I'm getting Key error in python
In my python program I am getting this error:
KeyError: 'variablename'
From this code:
path = meta_entry['path'].strip('/'),
Can anyone please explain why this is happening?
Solution 1:
A KeyError
generally means the key doesn't exist. So, are you sure the path
key exists?
From the official python docs:
exception KeyError
Raised when a mapping (dictionary) key is not found in the set of existing keys.
For example:
>>> mydict = {'a':'1','b':'2'}
>>> mydict['a']
'1'
>>> mydict['c']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>>
So, try to print the content of meta_entry
and check whether path
exists or not.
>>> mydict = {'a':'1','b':'2'}
>>> print mydict
{'a': '1', 'b': '2'}
Or, you can do:
>>> 'a' in mydict
True
>>> 'c' in mydict
False
Solution 2:
I fully agree with the Key error comments. You could also use the dictionary's get() method as well to avoid the exceptions. This could also be used to give a default path rather than None
as shown below.
>>> d = {"a":1, "b":2}
>>> x = d.get("A",None)
>>> print x
None