+= 1 tries to add 1 to some value which does not exist, hence the “key error: ‘o’”. Hint, you can make use of .get method. Or you can make use of defaultdict(int). Or you can just use Counter object in this week.
Cheers
P.S. this is not Course 1 Week 1 question if remember correctly, please post your question under correct category.
Actually that is not true because if we loop over a words and this is the first time we encounter the word, we should initialize it with 1.
Also, the for loop is not the most efficient way to get counts. Counter is probably the simplest way to get counts from list. (And we even would not have needed to initialize the dict in the first place).
The error the OP is getting is because the OP is trying to increment the values of the empty dict as @ai_curious pointed out (the very first step of the for loop)
Sure sure I removed to C2W1. Sorry for the mistake.
I tried to use .get() method, I write it like this: word_count_dict.get(word)+=1, but I get this error
something here.
before this line of code, I initialized the dictionary with keys as the unique words and values as 0. Since you mentioned, we can’t add 1 to nothing, when the first value is nothing.
{moderator edit: code removed}
There are myriad of ways to get “counts”, as I mentioned, one of the simplest and most used one is using Python object Counter (docs).
But to answer your question and not reveal the full solution, you can use .get()method on a dictionary in order not to use if statement, for example, if you want to increment “dog” count:
The problem causing the initial runtime error wasn’t that the value was nothing, rather it was related to an element with the provided key not being found.
dict[key] += 1
tells Python to do an indexed lookup on dict using key. Then, for the found element, increment the value. For an empty collection, the first part fails, so it cannot perform the second part.
My personal experience as a developer is that I have the most success if I write out the steps to follow, and write them in the most obvious and easy to test code implementation first. Then, after I know it is working, and if performance is an issue, look for ways to optimize the implementation. Trying to write the code straight away in the most terse way possible, for me at least, was a premature optimization that rarely paid off. YMMV