Why do I get a TypeError in this Python program?

53 Views Asked by At
# 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.

1

There are 1 best solutions below

0
On BEST ANSWER

If we debug:

message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    print(i) ### add this
    wordsRanking.setdefault(words[i], 0)
    wordsRanking[i] += 1   
print(wordsRanking)   

The output is that:

the ## this is what printed. and word[i] is now equal to word["the"]. that raise an error
Traceback (most recent call last):
  File "C:\Users\Dinçel\Desktop\start\try.py", line 6, in <module>
    wordsRanking.setdefault(words[i], 0)
TypeError: list indices must be integers or slices, not str

As you can see iterating words by for loop gives us elements of word. Not an integer or index of element. So you should use wordsRanking.setdefault(i, 0):

message = 'the of'
words = message.split()
wordsRanking = {}
for i in words:
    wordsRanking.setdefault(i, 0)
    wordsRanking[i] += 1   
print(wordsRanking)