Python Forum
Python2 to Python3 translation - .keys()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python2 to Python3 translation - .keys()
#1
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.
Reply
#2
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()
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Sad Migrating of python2 script to python3 zuri 7 966 Oct-05-2023, 02:40 PM
Last Post: snippsat
  Migration of Python2 and Python3 using Modernize and Future Rakshan 5 2,504 Oct-05-2023, 08:55 AM
Last Post: zuri
  Translation AliceCu 2 657 May-16-2023, 09:05 PM
Last Post: deanhystad
  Translation API snippyro 0 1,252 Nov-02-2021, 01:09 AM
Last Post: snippyro
  [GoogleTrans] How can i print my translation word ?... JamieVanCadsand 7 11,700 Aug-29-2021, 12:01 PM
Last Post: Melcu54
  python2 python3 messed up : How to fix ? hary 15 7,989 Dec-30-2020, 08:26 PM
Last Post: hary
  Translation of R Code to Python for Statistical Learning Course SterlingAesir 2 2,134 Aug-27-2020, 08:46 AM
Last Post: ndc85430
  Getting a small Python2 prog to run in Python3 steve140 4 3,862 Apr-19-2020, 09:27 AM
Last Post: steve140
  recording a translation table into a file arbiel 0 1,444 Mar-31-2020, 02:33 PM
Last Post: arbiel
  output mismatching when porting a python from python2 env to python3 env prayuktibid 2 2,552 Jan-21-2020, 04:41 AM
Last Post: prayuktibid

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020