Python 2 vs 3 gotcha: dict views

Python 3 changes something subtle in the core dict data type.

$ python2 -c 'print(type({}.items()))'
type 'list'
$ python3 -c 'print(type({}.items()))'
class 'dict_items'

The return type of dict.keys(), values(), and items() is no longer a simple list, it’s some fancy iterable. Unfortunately that iterable type doesn’t support other list methods like sorted. I guess the new type is more efficient, but it sure is a nuisance.

The simple workaround is to turn the result into a list.

sorted(list(myDict.items()))

But it’s more complicated than that, in fact there’s a whole PEP 469 about it.

Update: derp, I made a mistake. There’s no need to make the list, sorted(myDict.items()) works fine. However there are still other cases where you need to turn the dict_items type in to a real list.

I’m mostly having a good experience with Python 3 but run into weird little changes like this that bite you from time to time.