# I'm trying to make a Zipf's Law observation using a dictionary that stores every word, and a counter for it. I will later sort this from ascending to descending to prove Zipf's Law in a particular text. I'm taking most of this code from Automate the Boring Stuff with Python, where the same action is performed, but using letters instead.
message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
wordsRanking.setdefault(words[i], 0)
wordsRanking[i] += 1
print(wordsRanking)
This code gives me the following error:
TypeError: list indices must be integers or slices, not str
How do I resolve this? I would be really grateful.
If we debug:
The output is that:
As you can see iterating
words
by for loop gives us elements ofword
. Not an integer or index of element. So you should usewordsRanking.setdefault(i, 0)
: