aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Anand Krishna <[email protected]>2021-02-05 19:50:45 +0400
committerGravatar GitHub <[email protected]>2021-02-05 19:50:45 +0400
commit3a08d74e6ecc5a038ccfc97e973dac161171c6c2 (patch)
treebe60d08b1721cb706d2eca8a6bd2694a2883bfef
parentMerge pull request #1397 from python-discord/feat/1280/deleted-jumplink (diff)
Make `defaultdict` tag
-rw-r--r--bot/resources/tags/defaultdict.md20
1 files changed, 20 insertions, 0 deletions
diff --git a/bot/resources/tags/defaultdict.md b/bot/resources/tags/defaultdict.md
new file mode 100644
index 000000000..a15ebff2a
--- /dev/null
+++ b/bot/resources/tags/defaultdict.md
@@ -0,0 +1,20 @@
+**[`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict)**
+
+The Python `defaultdict` type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, the `defaultdict` will automatically create the key and generate a default value for it.
+While instantiating a `defaultdict`, we pass in a function that tells it how to create a default value for missing keys.
+
+```py
+>>> from collections import defaultdict
+>>> my_dict = defaultdict(int, {"foo": 1, "bar": 2})
+>>> print(my_dict)
+defaultdict(<class 'int'>, {'foo': 1, 'bar': 2})
+```
+
+In this example, we've used the `int` function - this means that if we try to access a non-existent key, it provides the default value of 0.
+
+```py
+>>> print(my_dict["foobar"])
+0
+>>> print(my_dict)
+defaultdict(<class 'int'>, {'foo': 1, 'bar': 2, 'foobar': 0})
+```