aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Xithrius <[email protected]>2021-02-11 00:06:41 -0800
committerGravatar GitHub <[email protected]>2021-02-11 00:06:41 -0800
commit2384a670dda3e63e9f6d16013de65eb8aa189d33 (patch)
tree5a8653a5c897406f3ace8a6242bcf8c8bd772e8b
parentMerge pull request #1401 from python-discord/bug/1371/moderation-check (diff)
parentMerge branch 'master' into patch-1 (diff)
Merge pull request #1398 from anand2312/patch-1
Make `KeyError` tag
-rw-r--r--bot/resources/tags/dict-get.md16
1 files changed, 16 insertions, 0 deletions
diff --git a/bot/resources/tags/dict-get.md b/bot/resources/tags/dict-get.md
new file mode 100644
index 000000000..e02df03ab
--- /dev/null
+++ b/bot/resources/tags/dict-get.md
@@ -0,0 +1,16 @@
+Often while using dictionaries in Python, you may run into `KeyErrors`. This error is raised when you try to access a key that isn't present in your dictionary. Python gives you some neat ways to handle them.
+
+**The `dict.get` method**
+
+The [`dict.get`](https://docs.python.org/3/library/stdtypes.html#dict.get) method will return the value for the key if it exists, and None (or a default value that you specify) if the key doesn't exist. Hence it will _never raise_ a KeyError.
+```py
+>>> my_dict = {"foo": 1, "bar": 2}
+>>> print(my_dict.get("foobar"))
+None
+```
+Below, 3 is the default value to be returned, because the key doesn't exist-
+```py
+>>> print(my_dict.get("foobar", 3))
+3
+```
+Some other methods for handling `KeyError`s gracefully are the [`dict.setdefault`](https://docs.python.org/3/library/stdtypes.html#dict.setdefault) method and [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) (check out the `!defaultdict` tag).