Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python 3 need dict.items to be wrapped with list()?

I'm using Python 3. I've just installed a Python IDE and I am curious about the following code warning:

features = { ... } for k, v in features.items():     print("%s=%s" % (k, v)) 

Warning is: "For Python3 support should look like ... list(features.items()) "

Also there is mention about this at http://docs.python.org/2/library/2to3.html#fixers

It also wraps existing usages of dict.items(), dict.keys(), and dict.values() in a call to list.

Why is this necessary?

like image 860
Dewfy Avatar asked Jul 17 '13 09:07

Dewfy


People also ask

Why we need to use dictionary when we already have list?

A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key. In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.

What is the benefit of a dict dictionary over a list?

It is more efficient to use a dictionary for lookup of elements because it takes less time to traverse in the dictionary than a list. For example, let's consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data.

Why would you use a dictionary over a list in Python?

Python dictionaries can be used when the data has a unique reference that can be associated with the value. As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn't be modified in the first place.

Why list Cannot be used as a dictionary key?

You cannot use a list as a key because a list is mutable. Similarly, you cannot use a tuple as a key if any of its elements are lists. (You can only use a tuple as a key if all of its elements are immutable.)


1 Answers

You can safely ignore this "extra precautions" warning: your code will work the same even without list in both versions of Python. It would run differently if you needed a list (but this is not the case): in fact, features.items() is a list in Python 2, but a view in Python 3. They work the same when used as an iterable, as in your example.

Now, the Python 2 to Python 3 conversion tool 2to3 errs on the side of safety, and assumes that you really wanted a list when you use dict.items(). This may not be the case (as in the question), in which case dict.items() in Python 3 (no wrapping list) is better (faster, and less memory-consuming, since no list is built).

Concretely, this means that Python 2 code can explicitly iterate over the view: for k, v in features.viewitems() (which will be converted in Python 3 by 2to3 to features.items()). It looks like your IDE thinks that the code is Python 2, because your for statement is very good, in Python 3, so there should be no warning about Python 3 support.

like image 152
Eric O Lebigot Avatar answered Oct 02 '22 20:10

Eric O Lebigot