Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
f7011b7b
Commit
f7011b7b
authored
Feb 19, 2007
by
Raymond Hettinger
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Provide an example of defaultdict with non-zero constant factory function.
parent
27bb8531
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
12 additions
and
8 deletions
+12
-8
Doc/lib/libcollections.tex
Doc/lib/libcollections.tex
+12
-8
No files found.
Doc/lib/libcollections.tex
View file @
f7011b7b
...
...
@@ -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
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment