Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm getting Key error in python

People also ask

How do I fix key errors in Python?

The Usual Solution: . If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.

Why am I getting a KeyError in Python?

exception KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys. So, try to print the content of meta_entry and check whether path exists or not.

How do you fix KeyError 0 in Python?

The Python "KeyError: 0" exception is caused when we try to access a 0 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.

What is TypeError in Python?

What is TypeError in Python? TypeError is an exception in Python programming language that occurs when the data type of objects in an operation is inappropriate. For example, If you attempt to divide an integer with a string, the data types of the integer and the string object will not be compatible.


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

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

For dict, just use

if key in dict

and don't use searching in key list

if key in dict.keys()

The latter will be more time-consuming.


Yes, it is most likely caused by non-exsistent key.

In my program, I used setdefault to mute this error, for efficiency concern. depending on how efficient is this line

>>>'a' in mydict.keys()  

I am new to Python too. In fact I have just learned it today. So forgive me on the ignorance of efficiency.

In Python 3, you can also use this function,

get(key[, default]) [function doc][1]

It is said that it will never raise a key error.


This means your array is missing the key you're looking for. I handle this with a function which either returns the value if it exists or it returns a default value instead.

def keyCheck(key, arr, default):
    if key in arr.keys():
        return arr[key]
    else:
        return default


myarray = {'key1':1, 'key2':2}

print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')

Output:

1
2
#default

I received this error when I was parsing dict with nested for:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cat:
        print(cats[cat][attr])

Traceback:

Traceback (most recent call last):
      File "<input>", line 3, in <module>
    KeyError: 'K'

Because in second loop should be cats[cat] instead just cat (what is just a key)

So:

cats = {'Tom': {'color': 'white', 'weight': 8}, 'Klakier': {'color': 'black', 'weight': 10}}
cat_attr = {}
for cat in cats:
    for attr in cats[cat]:
        print(cats[cat][attr])

Gives

black
10
white
8