261

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?

David Liaw
  • 3,193
  • 2
  • 18
  • 28
  • 15
    `Key error` generally means the `key` doesn't exist. So,are you sure 'path' exist.? – RanRag Apr 12 '12 at 02:13
  • 4
    Print the contents of `meta_entry` and ensure the key you want exists. – Makoto Apr 12 '12 at 02:14
  • 1
    > If you don't want to have an exception but would rather a default value used instead, you can use the get() method_, such as `path = meta_entry.get('path', None)`. This is useful if `path` is not guaranteed to be present. . See @Adam's [answer below](https://stackoverflow.com/a/10116571/1159167) and [KeyError](https://wiki.python.org/moin/KeyError). – Ricardo Nov 19 '21 at 19:29

8 Answers8

339

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
maxkoryukov
  • 4,205
  • 5
  • 33
  • 54
RanRag
  • 48,359
  • 38
  • 114
  • 167
  • hmm...how would I do that? (Sorry for being a noob) The app is hosted on google app engine and I don't have access to any files that it creates. – David Liaw Apr 12 '12 at 02:49
  • I have access to my code but none of the code that it creates or the engine uses – David Liaw Apr 12 '12 at 05:22
  • So, the code you posted `path = meta_entry['path'].strip('/'),` is it part of your code or the engine. If it is part of the engine i am afraid nothing can't be done. – RanRag Apr 12 '12 at 05:24
  • @lonehangman: than just do `print meta_entry` and check if it contains `path` or not. – RanRag Apr 15 '12 at 04:59
  • I'm quite new to python, could you please explain with more detail. Sorry for being a pest – David Liaw Apr 15 '12 at 05:08
  • @lonehangman: Can you please tell which part you are nt getting. – RanRag Apr 15 '12 at 05:10
  • Where to put >>> mydict = {'a':'1','b':'2'} >>> print mydict {'a': '1', 'b': '2'} – David Liaw Apr 15 '12 at 05:10
  • As you suggested that `path = meta_entry['path'].strip('/'),` is part of the code you wrote. So, it means `meta_entry` is also the part of your code. Now you are expecting a defined output when running your code. So, just `print` the contents of `meta_entry` by writing `print meta_entry` in your python code. and execute it to see the result. – RanRag Apr 15 '12 at 05:12
  • Ok I inserted the print meta_entry. Since I can't run it with python on my machine because it requires googles code I have to upload an run it. It works fine but I still get the error, where would meta_entry be printed to? – David Liaw Apr 15 '12 at 05:24
  • It should be printed on the browser when you hit the desired url. – RanRag Apr 15 '12 at 05:26
  • I suggest you take a look at [hello world gapp engine](https://developers.google.com/appengine/docs/python/gettingstarted/helloworld) and try to play with that example a little. It will help you in two ways : 1--> better understanding of gapp engine and 2--> how to debug it – RanRag Apr 15 '12 at 05:28
  • I left out a small detail...this error only happens when I upload a file from outside my browser(which is what I'm trying to achieve) – David Liaw Apr 15 '12 at 05:31
  • Can you explain what exactly do you mean by `outside the browser`. – RanRag Apr 15 '12 at 05:35
  • OK, I'm trying to make a way for files to be uploaded to dropbox without having to download software or use a browser to upload. For my tests I'm using windows network place. I can view and download files fine but I can't upload. – David Liaw Apr 15 '12 at 05:40
  • So why are you not using `dropbox python api`. I believe you can achieve you task by using that. Although I am not sure. – RanRag Apr 15 '12 at 05:42
  • That's something else...when I access the url it request for a username and password. I tried mine but that didn't work so is it possible to print to an external url or a file? – David Liaw Apr 15 '12 at 05:49
  • I tried printing meta_entry. That doesn't exist. I didn't read this: # make a fake Resource to ease our exporting – David Liaw Apr 15 '12 at 06:22
  • 1
    Adam Lewis solution is simple and efficient – Bheid Jan 16 '20 at 15:20
  • I am calculating the false positive data-points using if y_pred_set2[5]==0 and y_test[5]==1:, but it results in the key-error. According to your explanation, this should only occur if key is not found in the set of existing keys, but the keys I am using are indices, there shouldn't be this problem with them, right? – hansrajswapnil Feb 01 '21 at 10:35
161

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
Adam Lewis
  • 7,017
  • 7
  • 44
  • 62
  • 13
    +1 for very relevant .get() comment. Looks like a good application of the Python EAFP (Easier to Ask for Forgiveness than Permission) instead of LBYL (Look Before You Leap) which I think is less Pythonic. – Niels Bom Apr 24 '12 at 11:08
48

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.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
keywind
  • 1,135
  • 14
  • 24
6

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.

Glenn Yu
  • 613
  • 1
  • 7
  • 11
4

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'}
alper
  • 2,919
  • 9
  • 53
  • 102
Muthukumar
  • 554
  • 4
  • 9
3

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
pbaranski
  • 22,778
  • 19
  • 100
  • 117
2

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
Ben Sullins
  • 231
  • 2
  • 9
  • 11
    Argh... horrible, horrible unpythonic code. Don't write PHP code in Python: it's not an array, it's a dictionary (you may call it a hash, but array is right out). And: dicts already have your "keyCheck" function: instead of "keyCheck('key1', myarray, '#default')" you'd do "mydict.get('key1', '#default')" – Jürgen A. Erhard Feb 21 '17 at 09:21
0

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"))]()