Skip to content

Commit bf0f788

Browse files
committed
Create not_using_defaultdict.rst.
1 parent d7e52ac commit bf0f788

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
Not using ``defaultdict()``
2+
===========================
3+
4+
Summary
5+
-------
6+
7+
Rather than using ``if`` statements or ``for`` loops to initialize the keys of a dict, use the Python Standard Library built-in method ``defaultdict()`` to automatically initialize the value of every key in the dict. Using ``defaultdict()`` is more concise and less error-prone, as the programmer no longer has to remember to manually initialize the value of every key.
8+
9+
Description
10+
-----------
11+
12+
When a dict is created using ``defaultdict()``, the value for each key in the dict will default to the value provided as the first argument of ``defaultdict()``. This is more concise and less error-prone than manually setting the value of each key.
13+
14+
Examples
15+
----------
16+
17+
Manually initializing the keys of a dict
18+
........................................
19+
20+
The module below defines an empty dict and then manually initializes the keys of the dict. Although there is nothing wrong with this code, there is a more concise and less error-prone way to achieve the same idea.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
d = {}
27+
28+
if not "k" in d:
29+
d["k"] = 6
30+
31+
d["k"] += 1
32+
33+
print d["k"] # 7
34+
35+
Solutions
36+
---------
37+
38+
Use ``defaultdict()`` to initialize dict keys
39+
.............................................
40+
41+
The modified module below uses ``defaultdict`` to initialize the dict. Whenever a new key is created, the default value for that key is 6. This module is functionally equivalent to the previous module, but this one is more concise and less error-prone, because every key automatically initializes to 6 with no work on the part of the programmer.
42+
43+
.. code:: python
44+
45+
from collections import defaultdict
46+
47+
d = defaultdict(lambda : 6)
48+
d["k"] += 1
49+
50+
print d["k"] # 7
51+
52+
References
53+
----------
54+
- `Python Standard Library - collections.defaultdict <https://docs.python.org/2/library/collections.html#collections.defaultdict>`_

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy