Why do `key in dict` and `key in dict.keys()` have the same output?

后端 未结 2 969
逝去的感伤
逝去的感伤 2021-02-19 07:29

I tried to search the keys in a dictionary, but I forgot to add the keys() function. I still got the expected answer.

Why is the result the same for these t

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 08:10

    Python data model dictates that generally a membership test are normally implemented as an iteration through a sequence unless a container object supplies the special method __contains__ .

    As mentioned further in the document, for objects that does not implement the __contains__ special method, the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__().

    Its important to know that for dictionaries, dict.keys() returns either an iterator either a dictionary view (Python 3.X) or a sequence (more precisely a list), in Python (2.X). Membership test for a sequence/list is an O(n) complexity where as for a dictionary like object which is implemented as a hash map, or a dictionary view which supports operation like supports operations like membership test and iteration has a complexity of O(1).

    So for Python 2.X, there is a distinct difference in terms of what both does, that might impact performance, where as for Python 2.X, the only overhead is an extra function call.

    In any case, it is always preferred to use the membership on the dict object rather than using the membership test on a dictionary view or a sequence which is returned by dict.keys

提交回复
热议问题