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.
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.