I'd like to generate a defaultdict that contains a deque. For example:
d = defaultdict(deque)
The above work fine, but I'd like to make the deque a fixed length by passing in an argument:
d = defaultdict(deque(maxlen=10))
How can I pass arguments such as this to defaultdict?
Use a partially applied function:
from functools import partial
defaultdict(partial(deque, maxlen=10))
Demo:
>>> deque10 = partial(deque, maxlen=10)
>>> deque10()
deque([], maxlen=10)
>>> deque10(range(20))
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], maxlen=10)
See functools.partial
docs for details.
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