Jeremy Meyer Jeremy Meyer - 1 month ago 9
Python Question

Iterating over list slice in Python not working as expected

I've got this Python 3.5 code:

8 class MarkovDict:
...
13 def add(self, corpus=None):
14 if corpus == None:
15 return
16 prev_word = corpus[0]
17 for word in corpus[1:]:
18 self.dict[prev_word].append(word)
...


Should take
corpus
which is a list of strings.
Giving this error:

Traceback (most recent call last):
File "main.py", line 23, in <module>
main()
File "main.py", line 17, in main
bot = MarkovBot(full_markov_dict)
File "/Users/jeremy/code/markov/MarkovBot.py", line 5, in __init__
self.forward_dict = markov_dict.cloned()
File "/Users/jeremy/code/markov/MarkovDict.py", line 27, in cloned
return MarkovDict(copy.deepcopy(self.dict))
File "/Users/jeremy/code/markov/MarkovDict.py", line 11, in __init__
self.add(corpus)
File "/Users/jeremy/code/markov/MarkovDict.py", line 17, in add
for word in corpus[1:]:
TypeError: unhashable type: 'slice'


What am I missing?

Answer

Your corpus object is a dictionary rather than a list. When you try to index a dictionary with a slice, it knows that slices are an unhashable type that can never be added to a dictionary, so it tells you that right away.

Comments