pythondictionary

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

  • 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