[Python 3.1]
I want defaultdict(int)
, except I'd like the default value to be 1
rather than 0
.
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int.
defaultdict fills a specialized use-case, where you want values to be auto-created for you when a key is missing, and those values can be generated with a factory function without access to key being inserted. Note that exceptions are not just there to flag programmer error.
get method and the experiment shows that defaultdict more that two times faster than dict. get method.
>>> def f():
return 1
>>> a = defaultdict(f)
>>> a[1]
1
Here is an other implementation using lambda expression (from kindall):
>>> a = defaultdict(lambda: 1)
defaultdict(lambda: 1)
eg
>>> from collections import defaultdict
>>> a = defaultdict(lambda: 1)
>>> a["foo"] += 1
>>> a["foo"]
2
From the docs:
The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use itertools.repeat() which can supply any constant value (not just zero):
>>> def constant_factory(value):
... return itertools.repeat(value).next
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'
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