Search code examples
python-3.xpython-2.7python-2to3

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?


Solution

  • 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.