[Solved] Python Error: TypeError: ‘dict_keys’ object does not support indexing

Error message:

When learning the book machine learning practice, I ran according to the code in the book and made an error, but there was no error prompt in the code. The error codes are as follows:

firstStr = myTree.keys()[0]
print('树的叶子结点个数为:\n{}'.format(getNumLeafs(myTree)))

Errors are reported as follows:

firstStr = myTree.keys()[0]
TypeError: 'dict_keys' object does not support indexing

Type error: Dict_Keys object does not support indexing

The error is caused by different versions. The author uses version 2.X, while I use version 3.7.X.

Solution

For version 3.x, because python3 changed dict.keys, which returns a dict_keys object that supports iterable but not indexable, we can explicitly convert it to a list

Modify the error code as follows:

firstSides = list(myTree.keys()) 
firstStr = firstSides[0] 
# or 
firstStr = list(myTree.keys())[0] 

Just run it now.

Similar Posts: