SangminKim
SangminKim

Reputation: 9146

Should I convert dict.keys() into list(dict.keys()) for iteration in Python3?, 2to3 suggests converting that

I am doing a migration, Python2 to Pytnon3 with 2to3. (Python2.7.12 and Python3.5.2 exactly)

While doing the migration, 2to3 suggests I use type-cast like the below.

a = {1: 1, 2: 2, 3: 3}

for i in a.keys():  ----> for i in list(a.keys()):
    print(i)

After that, I try to check what difference there is in a script.

$ python3
>>> a = {1: 1, 2: 2, 3: 3}
>>> a.keys()
dict_keys([1, 2, 3])
>>> for i in a.keys(): print(i)
1
2
3

It apparently returns different type dict_keys not being list but dict_keys still seems to work with loop like list without type-cast in the above simple code.

I wonder If I use without type-cast, there would be some side-effect or not. If there is nothing, it looks unnecessary operation.

Why does 2to3 suggest that?

Upvotes: 2

Views: 4727

Answers (3)

Kevin
Kevin

Reputation: 1

I'm assuming this only became true recently, but now keys() is a list type, so I think type casting it to list does nothing, correct me if I'm wrong.

Edit: Nevermind, apparently the program I was using was on an old version of python. I tried on an updated version of python, and it returns type dict_keys.

Upvotes: 0

Eliethesaiyan
Eliethesaiyan

Reputation: 2322

here is a concrete example, in python3

a = {1: 1, 3: 2, 2: 3}
>>> a
{1: 1, 2: 3, 3: 2}
>>> a.keys()
dict_keys([1, 2, 3])
>>> type(a.keys())
<class 'dict_keys'>
>>> 

whereas in python 2

 a={1: 1, 2: 3, 3: 2}
>>> type(a.keys())
<type 'list'>
>>> 

as Grady said, for iteration everything works well but if you are designing an application that receives a list of keys in Python 2 and you port it to python 3 and apply to it list functions,it will definitely throw an error

Upvotes: 1

Grady Player
Grady Player

Reputation: 14549

Generally it doesn’t matter for iterating, but it does matter if you try to take an index, because keys() isn’t a list in py3, so you can’t take an index of it, it is generally a safe operation, know the cost of the list call, generally if it was ok in py2 it will be ok in py3.

Upvotes: 3

Related Questions