为什么 Python 的 dict.keys()返回的是列表而不是集合?

我希望 Python 的 key 方法返回一个集合而不是一个列表。因为它非常类似于散列表的键所提供的那种保证。具体来说,它们是唯一的,不像集合那样排序。但是,此方法返回一个列表:

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

这仅仅是 Python API 中的一个错误,还是我遗漏了其他原因?

78350 次浏览

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

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.