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?
The dict_items object is not a list, however, and does not have list methods, such as append() , index() , etc...
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.
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With