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.
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] += 1This will take the existing number for an item in your dictionary and add 1 to it.