【问题标题】:TypeError: 'dict_values' and dict_key object is not subscriptableTypeError: 'dict_values' 和 dict_key 对象不可下标
【发布时间】:2020-11-19 10:20:37
【问题描述】:

我遇到了一个导致错误的旧 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 in tree.values()[0].keys():
                print name, item
                self.printTree(tree.values()[0][item], name + "\t")
        else:
            print name, "\t->\t", tree

如何在使用 python 3x 时更改这些语法?我试过 list() 怎么self.printTree(tree.values()[0][item], name + "\t") 仍然有 dict_value 错误。

完整代码:https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch12/dtree.py

感谢您的帮助。

【问题讨论】:

  • 你的问题出在 python 3x 上,对吧?所以我认为共享 python 2 代码实际上是无关紧要的。为什么不发布实际上破坏并给出错误的python 3代码?
  • dict.keys() 在 python 3 中没有返回列表,因为它在 python 2 中使用过,因此出现错误。将tree.keys() 包装为list(tree.keys()) 或使用解包概括[*tree][0]。另见stackoverflow.com/a/45253740/909252
  • 我已将print (name, tree.keys()[0]) 更改为print (name, [*tree][0])。但是,for item in [*tree].values()[0]: 仍然会带出错误AttributeError: 'list' object has no attribute 'values'
  • 在这种情况下,[*tree] 是一个列表,因此没有 values 方法。 tree 是一本字典。学习决策树很有趣,但在学习更多 Python 之后,您可能会从中得到更多!

标签: python


【解决方案1】:

有很多选项可以做到这一点。这是我所知道的最短的:

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)

【讨论】:

    【解决方案2】:

    希望对你有用:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2017-07-15
      • 2021-10-01
      • 2019-12-07
      • 2012-01-09
      • 2021-11-23
      • 2012-02-21
      相关资源
      最近更新 更多