aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Anand Krishna <[email protected]>2021-02-06 23:28:04 +0400
committerGravatar GitHub <[email protected]>2021-02-06 23:28:04 +0400
commit5dc8f0e7e0cf150a9a89787b518fdbb7f8f2ba5c (patch)
tree484b4e24e21ba75ae14829355fd316f3171a2733
parentFix trailing whitespaces (diff)
Correct examples, reword description
-rw-r--r--bot/resources/tags/defaultdict.md17
1 files changed, 9 insertions, 8 deletions
diff --git a/bot/resources/tags/defaultdict.md b/bot/resources/tags/defaultdict.md
index 9361d6f2a..b6c3175fc 100644
--- a/bot/resources/tags/defaultdict.md
+++ b/bot/resources/tags/defaultdict.md
@@ -1,20 +1,21 @@
**[`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.
+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 insert 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})
+>>> my_dict = defaultdict(int)
+>>> my_dict
+defaultdict(<class 'int'>, {})
```
-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.
+In this example, we've used the `int` class which returns 0 when called like a function, so any missing key will get a default value of 0. You can also get an empty list by default with `list` or an empty string with `str`.
```py
->>> print(my_dict["foobar"])
+>>> my_dict["foo"]
0
->>> print(my_dict)
-defaultdict(<class 'int'>, {'foo': 1, 'bar': 2, 'foobar': 0})
+>>> my_dict["bar"] += 5
+>>> my_dict
+defaultdict(<class 'int'>, {'foo': 0, 'bar': 5})
```