Convert Python2 iterkeys() to python3

Question:

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?

Asked By: user1584421

||

Answers:

In python 3.x:

m = w.iterkeys().next()

would be equivalent to:

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

Answered By: Mr. Techie

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.

Answered By: Daweo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.