简体   繁体   中英

Convert Python2 iterkeys() to python3

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?

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 .

In python 3.x:

m = w.iterkeys().next()

would be equivalent to:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM