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:
- TypeError: ‘dict_keys’ object does not support indexing
- [Solved] Python error: attributeerror: type object ‘STR’ has no attribute ‘_name_’ (machine learning practice treeplotter code)
- Flask Accessing an interface that returns a dictionary error: The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict.
- How to Solve SQL fulltext error
- Django: How to Convert Models object to JSON
- Python3 urlopen() TypeError: can’t convert ‘bytes’ object to str im…
- PaddlePaddle Error: ‘map’ object is not subscriptable
- [Solved] TypeError: string indices must be integers, not str
- TypeError: list indices must be integers or slices, not str
- Python Pandas: Read_Excel() and to_Excel() function