[python] 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?

This question is related to python dictionary

The answer is


For example, if this is a number :

ouloulou={
    1:US,
    2:BR,
    3:FR
    }
ouloulou[1]()

It's work perfectly, but if you use for example :

ouloulou[input("select 1 2 or 3"]()

it's doesn't work, because your input return string '1'. So you need to use int()

ouloulou[int(input("select 1 2 or 3"))]()

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.


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.


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 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

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

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