diff options
| author | 2021-02-07 19:13:26 +0800 | |
|---|---|---|
| committer | 2021-02-07 19:13:26 +0800 | |
| commit | 6c2bd3c2b365f1030389c361cfcf1264116969f7 (patch) | |
| tree | b72a2b4cf7a9b76dab7890494d36be5667b16a52 | |
| parent | Merge pull request #1403 from python-discord/ks123/discord-py-local-file-tag (diff) | |
| parent | Merge branch 'master' into patch-2 (diff) | |
Merge pull request #1400 from anand2312/patch-2
Make `defaultdict` tag
| -rw-r--r-- | bot/resources/tags/defaultdict.md | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/bot/resources/tags/defaultdict.md b/bot/resources/tags/defaultdict.md new file mode 100644 index 000000000..b6c3175fc --- /dev/null +++ b/bot/resources/tags/defaultdict.md @@ -0,0 +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 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) +>>> my_dict +defaultdict(<class 'int'>, {}) +``` + +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 +>>> my_dict["foo"] +0 +>>> my_dict["bar"] += 5 +>>> my_dict +defaultdict(<class 'int'>, {'foo': 0, 'bar': 5}) +``` |