0

In python 3, a dict (or anything implementing the collections.Mapping interface) has a keys() method that returns a dict_keys, which is iterable (yielding keys, as __iter__() does) but can also respond to key in dict_keys in O(1) time (as __contains__ does).

But what else can dict_keys do for me that __iter__ and __contains__ doesn't already?

thorwhalen
  • 1,920
  • 14
  • 26
  • It can identify your object as a mapping. That's how dicts are duck typed in CPython. It could be done in other ways though, so that doesn't really justify it's existence. – Mad Physicist Jun 21 '19 at 15:03
  • 1
    It acts like a set in a few ways that dict doesn’t, so you can do `d.keys() & {"foo", "bar"}`, for example. I suppose you also get a guarantee that stuff you pass it to can’t modify your dict. – Ry- Jun 21 '19 at 15:05
  • It is a set-like view over the dictionaries keys. – juanpa.arrivillaga Jun 21 '19 at 16:34

0 Answers0