Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are dict_keys, dict_items and dict_values?

I came across these three types when I used collections.Counter's viewkeys(), viewitems() and viewvalues() methods.

The values those three methods returned are of types dict_keys, dict_items and dict_values.

They are iterable, as I have noticed.

But my question is, why do these three types exist? Or what's their usage?

like image 962
xiaohan2012 Avatar asked Sep 04 '11 00:09

xiaohan2012


People also ask

What is Dict_items?

The dict. items() returns a dictionary view object that provides a dynamic view of dictionary elements as a list of key-value pairs. This view object changes when the dictionary changes.

What is Dict_keys in Python?

dict. keys() function returns dict_keys - an iterable view of the dictionary's keys. You can iterate over dict_keys directly without converting it into a list. For many use cases, dict_keys can be dropped instead of a list in APIs, and it will work.


1 Answers

The What's new in 2.7 document is one place these are introduced. These "views" were introduced (proposed here) for Python 3 (and backported to 2.7, as you've seen) to serve as a best-of-all-worlds for the pieces of the dict they refer to.

Before we had the keys/values/items methods which simply made lists. This wastes memory by copying the dict's information and we had the iterkeys/itervalues/iteritems methods that didn't waste this memory but weren't very featureful (the only thing you could do is iterate over them, and you could only do so once). These new views have logical features, such as set operations, efficient comparison, and being iterable multiple times.

like image 139
Mike Graham Avatar answered Sep 23 '22 01:09

Mike Graham