I ran into some behaviour that suprised me a little today.
from collections import defaultdict
d = defaultdict(lambda: "test")
Now d[0]returns "test" as expected, but d.get(0) actually returns None. Is this expected behaviour?
I ran into some behaviour that suprised me a little today.
from collections import defaultdict
d = defaultdict(lambda: "test")
Now d[0]returns "test" as expected, but d.get(0) actually returns None. Is this expected behaviour?
Yes, this is expected. Aside from mydict[x], all other methods work exactly the same as a regular dict. From the documentation:
Return a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
The method it overrides is __missing__, and as further elaborated:
This method is called by the
__getitem__()method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by__getitem__().Note that
__missing__()is not called for any operations besides__getitem__(). This means thatget()will, like normal dictionaries, returnNoneas a default rather than using default_factory.
Emphasis added.
Yes, this is the expected, documented behaviour (emphasis in original):
Note that
__missing__()is not called for any operations besides__getitem__(). This means thatget()will, like normal dictionaries, returnNoneas a default rather than usingdefault_factory.