Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python's dict.keys() return a list and not a set?

I would've expected Python's keys method to return a set instead of a list. Since it most closely resembles the kind of guarantees that keys of a hashmap would give. Specifically, they are unique and not sorted, like a set. However, this method returns a list:

>>> d = {} >>> d.keys().__class__ <type 'list'> 

Is this just a mistake in the Python API or is there some other reason I am missing?

like image 370
oneself Avatar asked Dec 14 '12 20:12

oneself


People also ask

Is dict keys () a set?

In Python, the keys() and items() methods of dictionaries dict can be used to perform set operations on keys and key-value pairs. For example, you can generate a dictionary consisting of elements (keys and values) common to multiple dictionaries.

What does Python keys () return?

Python Dictionary keys() Method The keys() method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary, see example below.

What does dict keys () do in Python?

Python Dictionary keys() The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.

What is the return type of dict keys ()?

Python Dictionary keys() The dict. keys() method returns a dictionary view object that contains the list of keys of the dictionary.


1 Answers

One reason is that dict.keys() predates the introduction of sets into the language.

Note that the return type of dict.keys() has changed in Python 3: the function now returns a "set-like" view rather than a list.

For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

like image 135
NPE Avatar answered Oct 19 '22 04:10

NPE