Python how to solve KeyError: 2

46 Views Asked by At

So I am doing a problem in Codehs and I have run into a error for one of the problems. I am not very good at programming but I cannot figure out what I have done wrong. I keep getting the KeyError: 2 error every time and I have been debugging for a while. The code takes a user inputted string and prints how many times each word is used in the string and puts the amount into a dictionary along with its corresponding word as the key. When I input "hello hello" I get the KeyError: 2 error. The code should be below this message. Any and all help will help me, so thanks!

my_dict = {}
string = input("Enter a string: ")
string = string.split()
for value, item in enumerate(string):
    if string[value] in my_dict:
        my_dict.update({value : my_dict[value+1]})
    else:
        my_dict[item] = 1
    
print(my_dict)

I have tried many things like debugging and using prints but none showed any success.

2

There are 2 best solutions below

0
Jake Munson On

I believe line 6 is your issue, where you're trying to update the dictionary to show a string has appeared more than once. Try changing it to this:

my_dict[item] += 1

This will take the existing number for an item in your dictionary and add 1 to it.

0
simon On

In the update of your dictionary, you confused the key that you want to update (i.e. your substring item) and its index/position (value) in the split list (string). The following should fix it (replace the corresponding lines in your question's code):

if string[value] in my_dict:
    my_dict.update({item : my_dict[item]+1}) 

However, that's unnecessarily complicated, as you can directly update dictionary entries as follows:

if string[value] in my_dict:
    my_dict[item] += 1

Also note that you don't actually need the value that you produce with enumerate(): It simply increases by one for each substring in your split string – which does not really help you with counting duplicates. The way you currently use value can easily be replaced as follows:

for item in string:
    if item in my_dict:
        my_dict[item] += 1
    else:
        my_dict[item] = 1