Python defaultdict behaviour

Viewed 67

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?

2 Answers

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 that get() will, like normal dictionaries, return None as 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 that get() will, like normal dictionaries, return None as a default rather than using default_factory.

Related