In languages such as Python and Ruby, a KeyError is a specific exception type that is raised when a key could not be found within a dictionary (mapping). In Python, it is a subclass of LookupError. In Ruby, it is a subclass of IndexError.
Questions tagged [keyerror]
1165 questions
65
votes
7 answers
Python logging file config KeyError: 'formatters'
I'm currently working on a python project and I set up logging using a config file. It has already worked and was logging my messages as wanted.
But then, after rearranging some of the packages and modules, I only get a key error.
Full Traceback:
…

moritzrupp
- 833
- 2
- 9
- 11
44
votes
2 answers
Why do I get a KeyError when using pandas apply?
I'm working on the kaggle Outbrain competition, and all datasets referenced in my code can be found at https://www.kaggle.com/c/outbrain-click-prediction/data.
On to the problem: I have a dataframe with columns ['document_id', 'category_id',…

user133248
- 431
- 1
- 4
- 3
41
votes
3 answers
How do I avoid KeyError when working with dictionaries?
Right now I'm trying to code an assembler but I keep getting this error:
Traceback (most recent call last):
File "/Users/Douglas/Documents/NeWS.py", line 44, in
if item in registerTable[item]:
KeyError: 'LD'
I currently have this…

Wigan Pier
- 413
- 1
- 4
- 6
36
votes
6 answers
Python dictionary key error when assigning - how do I get around this?
I have a dictionary that I create like this:
myDict = {}
Then I like to add key in it that corresponds to another dictionary, in which I put another value:
myDict[2000]['hello'] = 50
So when I pass myDict[2000]['hello'] somewhere, it would give…

ulak blade
- 2,515
- 5
- 37
- 81
32
votes
4 answers
Default dict keys to avoid KeyError
I parsed some JSON data, creating bb_json, and am trying to write CSV data based on it to csv_writer. I have this code:
for product in bb_json['products']:
row = []
row.append(product['sku'])
if product['name']:
…

Kenfucious
- 397
- 1
- 5
- 9
31
votes
5 answers
KeyError: "None of [['', '']] are in the [columns]" pandas python
I would like to slice two columns in my data frame.
This is my code for doing this:
import pandas as pd
df = pd.read_csv('source.txt',header=0)
cidf = df.loc[:,['vocab','sumCI']]
This is a sample of data:
ID vocab sumCI sumnextCI …

sariii
- 2,020
- 6
- 29
- 57
31
votes
4 answers
Python dict.get('key') versus dict['key']
Why does this throw a KeyError:
d = dict()
d['xyz']
But this does not?
d = dict()
d.get('xyz')
I'm also curious if descriptors play a role here.

foundling
- 1,695
- 1
- 16
- 22
28
votes
3 answers
KeyError: 0 when accessing value in pandas series
In my script I have df['Time'] as shown below.
497 2017-08-06 11:00:00
548 2017-08-08 15:00:00
580 2017-08-10 04:00:00
646 2017-08-12 23:00:00
Name: Time, dtype: datetime64[ns]
But when i do
t1=pd.Timestamp(df['Time'][0])
I get an…

Bharat Sharma
- 1,081
- 3
- 11
- 23
28
votes
1 answer
KeyError: 'plotly_domain' when using plotly to do scatter plot in python
I'm using plotly to do scatter plot. The graph is generated on my account but the terminal still reports an error:
Traceback (most recent call last):
File "IEORE4709HW1.py", line 106, in
py.iplot(data, filename='basic-scatter')
File…

Jorvey
- 281
- 1
- 3
- 3
23
votes
4 answers
Python Key Error=0 - Can't find Dict error in code
basically I have been racking my brains for a good while now as to why my code is not working, I have tested parts separately and have look throughout the web to see if it can help, to no avail.
I am getting an error that the traceback is:
Traceback…

user3573321
- 243
- 1
- 3
- 6
21
votes
1 answer
Why does str(KeyError) add extra quotes?
Why does the string representation of KeyError add extra quotes to the error message? All other built-in exceptions just return the error message string directly.
For example, the following code:
print str(LookupError("foo"))
print…

pzed
- 817
- 5
- 8
19
votes
2 answers
python dictionary datetime as key, keyError
I'm trying to run a Python script using cron in Linux, which should construct a dictionary of data. I'm attempting to use datetime().now().time()as keys in the dictionary, but it seems to raise an error.
Can't the datetime type be used as a…

user3591675
- 399
- 1
- 4
- 15
16
votes
2 answers
Testing for KeyError
I'm trying to write a unit test that verifies a KeyError is created when a bad key is passed to a dictionary.
The code that raises the exception:
connections = SettingsManager().get_connections()
try:
connection =…

OpenDataAlex
- 1,375
- 5
- 19
- 39
14
votes
3 answers
getting raise KeyError(key) KeyError: 'SECRET_KEY' with django on production settings
I've 2 separate settings files for production and development and a common base.py settings file
base.py
SECRET_KEY = r"!@#$%^&123456"
prod.py
from .base import *
SECRET_KEY = os.environ['SECRET_KEY']
manage.py
#!/usr/bin/env python
import…

sidx
- 640
- 2
- 11
- 28
13
votes
1 answer
When should I raise LookupError in python?
Python's built-in exception documentation defines LookupError as:
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by…

Veltzer Doron
- 934
- 2
- 10
- 31