Python Forum

Full Version: Python2 to Python3 translation - .keys()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm trying to follow the code in a machine learning textbook. Unfortunately, the code is written in Python2, and I'm using IPython via neovim, so I have to use Python 3.

The full code can be found here.

The code won't run in Python3 without some adjustments to the printTree() function.

Original:
	
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
My edits:
	
def printTree(self,tree,name):
	if type(tree) == dict:
		print(name, list(tree.keys())[0])
		for item in list(list(tree.values())[0].keys()):
			print(name, item)
	else:
		print(name, "\t->\t", tree)
Alas, I still get an error when I run the code:
Output:
154 def printTree(self,tree,name): 155 if type(tree) == dict: --> 156 print(name, list(tree.keys())[0]) 157 for item in list(list(tree.values())[0].keys()): 158 print(name, item) TypeError: 'dict_keys' object does not support indexing
The puzzling thing is that I don't get the indexing error if I run the same code outside of a function. I am at a bit of a loss with how to resolve this.
dict.keys returns a view not a list in python3.x
http://btmiller.com/2015/04/13/get-list-...and-3.html

You shoudl also use isinstance instead of type()