Home > Software design >  Convert Python2 iterkeys() to python3
Convert Python2 iterkeys() to python3

Time:08-06

I have this line from python2 code:

m = w.iterkeys().next();

When trying to run this, I get:

AttributeError: 'collections.OrderedDict' object has no attribute 'iterkeys'

I found out that iterkeys is not supported in Python3.

How to convert this line, in order to be compatible with Python3?

CodePudding user response:

There exist tool for such conversion called 2to3 let say you have code.py file with content as follows

import collections
w = collections.OrderedDict(a=1,b=2,c=3)
m = w.iterkeys().next();
print m

then open terminal and do 2to3 -w code.py, this does alter code.py to

import collections
w = collections.OrderedDict(a=1,b=2,c=3)
m = next(iter(w.keys()));
print(m)

which could be used with python3. Original is kept as code.py.bak.

CodePudding user response:

In python 3.x:

m = w.iterkeys().next()

would be equivalent to:

m = list(w.keys())[0]

  • Related