diff options
author | Raymond Hettinger <python@rcn.com> | 2007-02-19 19:26:16 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2007-02-19 19:26:16 (GMT) |
commit | b66d33fcd0e9dcc0cdf8e9e29d73a7c05d643f54 (patch) | |
tree | 86770fc401fde2ee459e0a2278f4e8002e77f093 /Doc | |
parent | 1bff7969832877398b129a97ad8d307c27c80fba (diff) | |
download | cpython-b66d33fcd0e9dcc0cdf8e9e29d73a7c05d643f54.zip cpython-b66d33fcd0e9dcc0cdf8e9e29d73a7c05d643f54.tar.gz cpython-b66d33fcd0e9dcc0cdf8e9e29d73a7c05d643f54.tar.bz2 |
Provide an example of defaultdict with non-zero constant factory function.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/lib/libcollections.tex | 20 |
1 files changed, 12 insertions, 8 deletions
diff --git a/Doc/lib/libcollections.tex b/Doc/lib/libcollections.tex index 3e56a3e..a763e31 100644 --- a/Doc/lib/libcollections.tex +++ b/Doc/lib/libcollections.tex @@ -311,16 +311,20 @@ languages): 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 count of zero. The increment operation then builds up the count for each -letter. This technique makes counting simpler and faster than an equivalent -technique using \method{dict.get()}: +letter. -\begin{verbatim} ->>> d = {} ->>> for k in s: - d[k] = d.get(k, 0) + 1 +The function \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 \function{itertools.repeat()} which can supply +any constant value (not just zero): ->>> d.items() -[('i', 4), ('p', 2), ('s', 4), ('m', 1)] +\begin{verbatim} +>>> 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} Setting the \member{default_factory} to \class{set} makes the |