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

PythonPython 2.x

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 - Python

In python 2, it's less efficient to construct a set than a list.

Don't want to make an assumption that the user of the return value will want to search within the result. Iteration is also likely.

In python 3, it's no longer a list. It's an ordered iterable because ordering is guaranteed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiononeselfView Question on Stackoverflow
Solution 1 - PythonNPEView Answer on Stackoverflow
Solution 2 - PythonErik AronestyView Answer on Stackoverflow