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?


Solution 1:

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 ^).

Solution 2:

Because the ordering is guaranteed.

In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

In Python 3.6, it's ordered if you use cpython.

In earlier versions, probably everyone was hoping for 3.7

In