Tag Archives: treePlotter

[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.

[Solved] Python error: attributeerror: type object ‘STR’ has no attribute ‘_name_’ (machine learning practice treeplotter code)

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:

if type(secondDict[key])._name_ == 'dict':

Errors are reported as follows:

AttributeError: type object 'str' has no attribute '_name_'

Attribute error: the type object “STR” has no attribute “name”,

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

Solution

The type object “STR” in Python 3 does not have the “_name_” attribute, so we need to remove the attribute. In addition, this judgment statement was originally used to judge whether the node type is dict (Dictionary), but because the single quotation mark (”) is added, it becomes a string, which will cause other errors, so we also need to remove the single quotation mark.

Modify the error code as follows:

if type(secondDict[key]) == dict:

Just run it now.