Python 类型错误:';dict#u值';并且dict_key对象不可下标
我遇到了一个旧python 2x代码语法的问题,导致了错误:Python 类型错误:';dict#u值';并且dict_key对象不可下标,python,Python,我遇到了一个旧python 2x代码语法的问题,导致了错误: print (name, tree.keys()[0]) TypeError: 'dict_keys' object is not subscriptable 旧的python 2x代码是: def printTree(self,tree,name): if type(tree) == dict: print name, tree.keys()[0] for item
print (name, tree.keys()[0])
TypeError: 'dict_keys' object is not subscriptable
旧的python 2x代码是:
def printTree(self,tree,name):
if type(tree) == dict:
print name, tree.keys()[0]
for item in tree.values()[0].keys():
print name, item
self.printTree(tree.values()[0][item], name + "\t")
else:
print name, "\t->\t", tree
在使用python3x时如何更改这些语法?我尝试了list(),self.printTree(tree.values()[0][item],name+“\t”)
仍然存在dict\u值错误
完整代码:
谢谢你的帮助。有很多选择。以下是我知道的最短的:
d = {1:2, 3:4}
list(d.keys())[0] # option 1
next(iter(d.keys())) # option 2
next(iter(d)) # option 3 - works only on keys (iteration over a dictionary is an iteration over its keys)
有很多选择可以做到这一点。以下是我知道的最短的:
d = {1:2, 3:4}
list(d.keys())[0] # option 1
next(iter(d.keys())) # option 2
next(iter(d)) # option 3 - works only on keys (iteration over a dictionary is an iteration over its keys)
我希望它会有用:
def printTree(products):
if type(products) == dict:
print(list(products.keys())[0])
for item in products.values():
print(item)
self.printTree(products.values()[0][item], name + "\t")
else:
print("\t->\t", products)
我希望它会有用:
def printTree(products):
if type(products) == dict:
print(list(products.keys())[0])
for item in products.values():
print(item)
self.printTree(products.values()[0][item], name + "\t")
else:
print("\t->\t", products)
你的问题是python3x,对吗?因此,我认为共享Python2代码实际上是无关紧要的。为什么不发布实际中断并给出错误的Python3代码?
dict.keys()
在Python3中不会像在Python2中那样返回列表,因此会出现错误。将tree.keys()
包装为列表(tree.keys())
或使用解包概括法[*tree][0]
。另请参见我已将print(name,tree.keys()[0])
更改为print(name,[*tree][0])
。但是,[*tree].values()[0]:中的项的仍然会显示错误AttributeError:“list”对象没有属性“values”
在此上下文中,[*tree]
是一个列表,因此没有values
方法<代码>树
是一本字典,它也是。学习决策树很有趣,但在学习更多Python之后,您可能会从中获得更多!这回答了你的问题吗?你的问题是python3x,对吗?因此,我认为共享Python2代码实际上是无关紧要的。为什么不发布实际中断并给出错误的Python3代码?dict.keys()
在Python3中不会像在Python2中那样返回列表,因此会出现错误。将tree.keys()
包装为列表(tree.keys())
或使用解包概括法[*tree][0]
。另请参见我已将print(name,tree.keys()[0])
更改为print(name,[*tree][0])
。但是,[*tree].values()[0]:中的项的仍然会显示错误AttributeError:“list”对象没有属性“values”
在此上下文中,[*tree]
是一个列表,因此没有values
方法<代码>树
是一本字典,它也是。学习决策树很有趣,但在学习更多Python之后,您可能会从中获得更多!这回答了你的问题吗?