Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.index() generates AttributeError: 'dict_values' object has no attribute 'index'

Tags:

python

I'm trying to rewrite this Python2 code to Python3 accepted syntax. The .index() methods generates the following error:

AttributeError: 'dict_values' object has no attribute 'index'

This is because .index() is no valid syntax in Python3. I've read that a list should be used to work around the problem, but I can't figure out how to do it. Anyone any idea how to work around the problem?

words1 = [self._word_to_id.keys()[self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1)]
indices = [i for i, w in enumerate(words1) if w in PUNCTUATIONS]
for i in indices:
    words1[i], words1[i-1] = words1[i-1], words1[i] 
words2 = [self._word_to_id.keys([self._word_to_id.values().index(data_x[index])] for index in range(len(puncts) - 1, len(data_x))]
all_words = words1 + [puncts[-1]] + words2  
content = ' '.join(all_words)  
min_step = len(puncts)
like image 866
Wolfgang Plato Avatar asked Mar 01 '18 14:03

Wolfgang Plato


2 Answers

You are calling self._word_to_id.values() which returns the class dict_values and not list. dict_values does not inherit from list and does not have the index method because of that.

You need to convert your dictionary values into a list to use the index function. Try this:

list(self._word_to_id.values()).index(data_x[index])
like image 111
jsmolka Avatar answered Nov 13 '22 06:11

jsmolka


words1 = [list(self._word_to_id.keys())[list(self._word_to_id.values()).index(data_x[index])] for index in range(len(puncts) - 1)]

like image 2
Wolfgang Plato Avatar answered Nov 13 '22 04:11

Wolfgang Plato