Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict with a parameter to the class constructor

[Python 3.1]

I want defaultdict(int), except I'd like the default value to be 1 rather than 0.

  1. Is there any neat way to do that?
  2. Should I do that?
like image 985
max Avatar asked Nov 10 '10 00:11

max


People also ask

How does Defaultdict work How does Defaultdict work?

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.

What does Defaultdict mean?

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.

Why should I use Defaultdict?

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.

Is Defaultdict faster than dict?

get method and the experiment shows that defaultdict more that two times faster than dict. get method.


3 Answers

>>> def f():
        return 1
>>> a = defaultdict(f)
>>> a[1]
1

Here is an other implementation using lambda expression (from kindall):

>>> a = defaultdict(lambda: 1)
like image 76
mouad Avatar answered Oct 20 '22 23:10

mouad


defaultdict(lambda: 1)

eg

>>> from collections import defaultdict
>>> a = defaultdict(lambda: 1)
>>> a["foo"] += 1
>>> a["foo"]
2
like image 20
John La Rooy Avatar answered Oct 21 '22 01:10

John La Rooy


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>'
like image 1
Falmarri Avatar answered Oct 21 '22 01:10

Falmarri