1

I met a problem with a old python 2x code syntax which produced the error:

print (name, tree.keys()[0])
TypeError: 'dict_keys' object is not subscriptable

and the old python 2x code is:

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

How can I change these syntax in using python 3x? I have tried list() how ever the self.printTree(tree.values()[0][item], name + "\t") still has the dict_value error.

The full code: https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch12/dtree.py

Thank you for your help.

Steven
  • 2,658
  • 14
  • 15
Thien Hua
  • 45
  • 1
  • 6
  • 2
    Your problem is with python 3x right? So sharing python 2 code is actually kind of irrelevant I think. Why don't you post the python 3 code that is actually breaking and giving the error? – Ananda Nov 19 '20 at 10:28
  • 1
    `dict.keys()` does not return a list in python 3, as it used to in python 2, hence the error. Wrap `tree.keys()` as `list(tree.keys())` or use unpacking generalisations `[*tree][0]`. See also https://stackoverflow.com/a/45253740/909252 – Steven Nov 19 '20 at 10:34
  • I have changed ```print (name, tree.keys()[0])``` to ```print (name, [*tree][0])```. However, the ```for item in [*tree].values()[0]:``` still bring out the error ```AttributeError: 'list' object has no attribute 'values'``` – Thien Hua Nov 19 '20 at 10:47
  • In this context, `[*tree]` is a list so does not have a `values` method. `tree` is a dictionary so does. Decision Trees are fun to learn about but you may get more from it after learning a bit more Python! – Steven Nov 19 '20 at 14:12
  • 1
    Does this answer your question? [Python: how to convert a dictionary into a subscriptable array?](https://stackoverflow.com/questions/33674033/python-how-to-convert-a-dictionary-into-a-subscriptable-array) – Steven Nov 19 '20 at 14:14

2 Answers2

3

There are many options to do it. Here are the shortest I know:

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)
saart
  • 344
  • 1
  • 5
0

I hope it will be useful:

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)