67

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?

1

5 Answers 5

58

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.

9
  • 7
    Note: in general, it is not safe to ignore the warning if the loop modifies the dict. It breaks on Python 3 without list().
    – jfs
    Commented Jul 17, 2013 at 18:28
  • This should never happen: a loop normally cannot modify the dictionary it is iterating over; this generally raises a RuntimeError: dictionary changed size during iteration (both in Python 2 and Python 3). Reference: docs.python.org/dev/whatsnew/2.7.html#pep-3106-dictionary-views Commented Jul 18, 2013 at 2:45
  • 1
    This doesn't explain why a list is necessary, which is required by the main question. Commented Jul 31, 2018 at 19:54
  • 1
    Can you elaborate on this? The answer to the original question is that list() is not necessary. A longer answer is that if the features dictionary of the original question were modified in the loop, then list() would effectively freeze the list of items and the dictionary could be modified in the loop (iterating over a view of the items in a dictionary that changes may raise an exception). Commented Aug 1, 2018 at 15:15
  • 1
    The key phrase in this answer is when used as an iterable
    – cowlinator
    Commented Mar 26, 2019 at 23:38
56

In Python 2, the methods items(), keys() and values() used to "take a snapshot" of the dictionary contents and return it as a list. It meant that if the dictionary changed while you were iterating over the list, the contents in the list would not change.

In Python 3, these methods return a view object whose contents change dynamically as the dictionary changes. Therefore, in order for the behavior of iterations over the result of these methods to remain consistent with previous versions, an additional call to list() has to be performed in Python 3 to "take a snapshot" of the view object contents.

3
  • Thank you for the answer and (+1) of course, but this derive one more question on it: ... change dynamically ... If I'm ok with dynamic changes, do Python provides safe iteration over it (just compare with java behavior - raise exception from iterator on changing container)
    – Dewfy
    Commented Jul 17, 2013 at 12:19
  • 2
    @Dewfy, not really. The view objects themselves are safe, but as soon as you create iterators from them and use these iterators in loops, adding or removing entries from the source dictionary may lead to errors or "miss" entries. The documentation says iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries. Commented Jul 17, 2013 at 12:33
  • 1
    This should be the accepted answer, since it actually answers the question. Commented Jul 31, 2018 at 19:55
7

Python 3 returns a Dictionary View Object rather than a list which Python 2 would return and some operators that you would expect may not be true - also a View Object will change if the underlying dictionary changes, (possibly in the code that you are iterating through which could cause some unwelcome surprises).

3

In Python 3, dict.items(), dict.keys(), and dict.values() are iterators. Therefore if you are expecting a list, you might get some errors when doing operations that work on lists, but not necessarily on iterators, such as len(dict.items()) (will generate a TypeError).

CORRECTION

The dict_items returned by calling dict.items() in Python 3 does indeed have a __len__() and will not generate a TypeError. The dict_items object is not a list, however, and does not have list methods, such as append(), index(), etc...

Also, as the other (I would say much better) answers by Hamidi and Barnes state, dict_items is a view object that will dynamically change when the dict is altered.

5
  • 3
    Nitpick: It is not technically correct that dict.items() etc. are iterators in Python 3: they are iterable, meaning that they can be converted into iterators. Reference: docs.python.org/2/glossary.html Commented Jul 17, 2013 at 9:22
  • 1
    Major Nitpick - len(dict.items()) should be len(dictview) which is specifically given as an example in the documentation, docs.python.org/3/library/stdtypes.html#dict.items, while this answer incorrectly states that it will NOT work and will generate a type error. Commented Jul 17, 2013 at 15:09
  • 1
    @SteveBarnes: You're absolutely right. I should have checked the docs before attempting to answer. Commented Jul 17, 2013 at 18:20
  • I'm surprised that my answer, which was just plain wrong, actually received upvotes. Commented Jul 17, 2013 at 18:23
  • Very Gracious @JoelCornett Commented Jul 17, 2013 at 18:29
3

When converting a project to python 3 using 2to3, you can disable this by excluding the dict fixer for more concise output:

$ 2to3 -x dict *

Watch out for iteritems(), iterkeys() https://docs.python.org/2/library/2to3.html#2to3fixer-dict and fix by hand.

2
  • 5
    Question is not about "how to close an eye", it was about the root cause
    – Dewfy
    Commented Feb 4, 2015 at 14:10
  • True, I just shared this because in retrospect I wish I knew it earlier.
    – fmalina
    Commented Feb 4, 2015 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.