The class collections.defaultdict
takes a default factory, used to generate a default value.
If the values contained in the dict
-like object should default to False
, the instance can be created as:
d_false = defaultdict(bool)
What is the most pythonic way to achieve the same for a default value of True
?
In other terms, is there a standard callable object returning True
which is idiomatically used as the relative of bool
?
Of course, the factory could be built as a lambda expression:
d_true = defaultdict(lambda: True)
but this might be reinventing the wheel.
We could use partial
as an alternative to lambda
:
from functools import partial
from collections import defaultdict
d_true = defaultdict(partial(bool, True))
print(d_true['bona fide'])
(Which is also Python 2 friendly.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With