Commit 3a74f864 authored by Raymond Hettinger's avatar Raymond Hettinger

Provide an example of defaultdict with non-zero constant factory function.

parent a4aaf2bc
...@@ -311,16 +311,20 @@ languages): ...@@ -311,16 +311,20 @@ languages):
When a letter is first encountered, it is missing from the mapping, so the When a letter is first encountered, it is missing from the mapping, so the
\member{default_factory} function calls \function{int()} to supply a default \member{default_factory} function calls \function{int()} to supply a default
count of zero. The increment operation then builds up the count for each count of zero. The increment operation then builds up the count for each
letter. This technique makes counting simpler and faster than an equivalent letter.
technique using \method{dict.get()}:
\begin{verbatim} The function \function{int()} which always returns zero is just a special
>>> d = {} case of constant functions. A faster and more flexible way to create
>>> for k in s: constant functions is to use \function{itertools.repeat()} which can supply
d[k] = d.get(k, 0) + 1 any constant value (not just zero):
>>> d.items() \begin{verbatim}
[('i', 4), ('p', 2), ('s', 4), ('m', 1)] >>> 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>'
\end{verbatim} \end{verbatim}
Setting the \member{default_factory} to \class{set} makes the Setting the \member{default_factory} to \class{set} makes the
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment