Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 2to3 change mydict.keys() to list(mydict.keys())?

I'm looking at an output from 2to3 that includes this change:

-            for file_prefix in output.keys():
+            for file_prefix in list(output.keys()):

where output is a dictionary.

What is the significance of this change? Why does 2to3 do this?

How does this change make the code Python 3 compatible?

like image 229
Praxeolitic Avatar asked Dec 15 '14 01:12

Praxeolitic


People also ask

Is Dict_items a list?

The dict_items object is not a list, however, and does not have list methods, such as append() , index() , etc...

How can I get a list of all keys in a dictionary?

Method 1: Get dictionary keys as a list using dict. The dict. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.

What is Python 2to3?

2to3 is a Python program that reads Python 2. x source code and applies a series of fixers to transform it into valid Python 3. x code. The standard library contains a rich set of fixers that will handle almost all code.


2 Answers

In Python 3, the .keys() method returns a view object rather than a list, for efficiency's sake.

In the iteration case, this doesn't actually matter, but where it would matter is if you were doing something like foo.keys()[0] - you can't index a view. Thus, 2to3 always adds an explicit list conversion to make sure that any potential indexing doesn't break.

You can manually remove the list() call anywhere that a view would work fine; 2to3 just isn't smart enough to tell which case is which.

(Note that the 2.x version could call iterkeys() instead, since it's not indexing.)

like image 84
Amber Avatar answered Oct 01 '22 18:10

Amber


In Python 2.x, dict.keys() returns a list.

In Python 3.x, dict.keys() returns a view and must be passed to list() in order to make it a list.

Since the Python 2.x code doesn't need a list it should call dict.iterkeys() instead.

like image 31
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 16:10

Ignacio Vazquez-Abrams