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

戏子无情 提交于 2019-12-18 11:14:57

问题


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?


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



来源:https://stackoverflow.com/questions/13886129/why-does-pythons-dict-keys-return-a-list-and-not-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!