Python KeyError: 'kiwi'
KeyError: 'kiwi'
You get this error when you try to read a value from a dictionary with a key it does not have. What follows KeyError: is the key you were looking for. Check that the key is really in the dictionary and that its spelling and type are the same.
Cause 1. You looked up a key that is not there
d[key] only works when the key exists. A key you never added, a key spelled differently and a key with different upper or lower case ("Apple" and "apple") are all missing keys.
Wrong code
prices = {"apple": 500, "banana": 300}print(prices["kiwi"])Traceback (most recent call last): File "main.py", line 2, in <module> KeyError: 'kiwi'
Fixed code
Ask with in whether the key is there before you read it, or use get. When the key is missing, get returns the default you gave as its second argument instead of raising an error (None if you gave none).
prices = {"apple": 500, "banana": 300}if "kiwi" in prices: print(prices["kiwi"])else: print("no kiwi")print(prices.get("kiwi", 0))no kiwi 0
Cause 2. You did += 1 on a key you had not seen yet
This comes up a lot when counting. count[ch] += 1 reads count[ch] first, then adds 1 and stores it, so a character that appears for the first time has no value to read.
Wrong code
count = {}for ch in "banana": count[ch] += 1print(count)Traceback (most recent call last): File "main.py", line 3, in <module> KeyError: 'b'
Fixed code
Use get(ch, 0) so that it starts from "0 if missing".
count = {}for ch in "banana": count[ch] = count.get(ch, 0) + 1print(count){'b': 1, 'a': 3, 'n': 2}Cause 3. The key has a different type
The number 2 and the string "2" are different keys. input() always returns a string, so if you look it up as it is in a dictionary whose keys are numbers, the key is not found. When the error message has quotes, as in KeyError: '2', it means you looked up a string.
Wrong code
names = {1: "one", 2: "two", 3: "three"}n = input()print(names[n])2
Traceback (most recent call last): File "main.py", line 3, in <module> KeyError: '2'
Fixed code
Convert it to the same type as the dictionary's keys before you look it up.
names = {1: "one", 2: "two", 3: "three"}n = int(input())print(names[n])2
two
What to check when you see this error
- The value after
KeyError:is the key you were looking for. With quotes it is a string, without quotes it is a number. - Put
print(d.keys())right above the line where the error happened (the number afterline) to see which keys are really in there. - Check that the spelling, the upper and lower case, and the spaces at either end are the same. If the key came from input, try removing the spaces with
strip(). - Where a key may be missing, ask with
infirst or useget.