I'm getting Key error in python
Asked Answered
L

8

270

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?

Liederman answered 12/4, 2012 at 2:11 Comment(3)
Key error generally means the key doesn't exist. So,are you sure 'path' exist.?Loyola
Print the contents of meta_entry and ensure the key you want exists.Biscay
> 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 and KeyError.Ocotillo
L
347

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
Loyola answered 12/4, 2012 at 2:15 Comment(19)
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.Liederman
I have access to my code but none of the code that it creates or the engine usesLiederman
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.Loyola
@lonehangman: than just do print meta_entry and check if it contains path or not.Loyola
I'm quite new to python, could you please explain with more detail. Sorry for being a pestLiederman
@lonehangman: Can you please tell which part you are nt getting.Loyola
Where to put >>> mydict = {'a':'1','b':'2'} >>> print mydict {'a': '1', 'b': '2'}Liederman
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.Loyola
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?Liederman
It should be printed on the browser when you hit the desired url.Loyola
I suggest you take a look at hello world gapp engine 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 itLoyola
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)Liederman
Can you explain what exactly do you mean by outside the browser.Loyola
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.Liederman
So why are you not using dropbox python api. I believe you can achieve you task by using that. Although I am not sure.Loyola
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?Liederman
I tried printing meta_entry. That doesn't exist. I didn't read this: # make a fake Resource to ease our exportingLiederman
Adam Lewis solution is simple and efficientDysphonia
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?Fabianfabianism
V
167

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
Violoncellist answered 12/4, 2012 at 2:20 Comment(1)
+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.Provincialism
P
50

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.

Pileup answered 18/2, 2016 at 15:2 Comment(0)
C
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.

Cornellcornelle answered 10/1, 2013 at 21:44 Comment(1)
The get method is ancient, I think even 1.x dicts had it. But I'm sure 2.7 already had it.Squatter
K
5

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'}
Kathie answered 29/6, 2020 at 4:24 Comment(0)
C
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
Cartulary answered 8/2, 2018 at 12:25 Comment(0)
R
1

This means your dictionary 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
Rhenium answered 1/8, 2013 at 0:31 Comment(1)
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')"Squatter
C
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"))]()
Canyon answered 2/8, 2019 at 22:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.