Suppose I want to create a dict
(or dict
-like object) that returns a default value if I attempt to access a key that's not in the dict
.
I can do this either by using a defaultdict
:
from collections import defaultdict
foo = defaultdict(lambda: "bar")
print(foo["hello"]) # "bar"
or by using a regular dict
and always using dict.get(key, default)
to retrieve values:
foo = dict()
print(foo.get("hello", "bar")) # "bar"
print(foo["hello"]) # KeyError (as expected)
Other than the obvious ergonomic overhead of having to remember to use .get()
with a default value instead of the expected bracket syntax, what's the difference between these 2 approaches?