From 69e5e3776b3dedcb3570d58a27a1f6c80d3e2385 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Fri, 16 Oct 2020 21:30:49 +0300 Subject: [PATCH] Add key_in_dict --- snippets/key_in_dict.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 snippets/key_in_dict.md diff --git a/snippets/key_in_dict.md b/snippets/key_in_dict.md new file mode 100644 index 000000000..24c33423f --- /dev/null +++ b/snippets/key_in_dict.md @@ -0,0 +1,18 @@ +--- +title: key_in_dict +tags: dictionary,beginner +--- + +Checks if the given key exists in a dictionary. + +- Use the `in` operator to check if `d` contains `key`. + +```py +def key_in_dict(d, key): + return (key in d) +``` + +```py +d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} +key_in_dict(d, 'three') # True +```