キーの存在確認
Coddyの「Pythonの辞書」コースのレッスン 8/14。
辞書内に指定されたキーが存在するかどうかを判定するには、in キーワードを使用します。
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print("name" in my_dict) # キーが存在するかどうかを確認し、True を出力しますチャレンジ
簡単単語とその意味のコレクションを表す辞書が与えられています。あなたのタスクは、与えられた単語が辞書内に存在するかどうかをチェックする、find_meaning という名前の関数を作成することです。
自分で試してみよう
# 単語とその意味の辞書
word_meanings = {
"apple": "a fruit",
"book": "a written or printed work",
"car": "a motor vehicle with four wheels",
"dog": "a domesticated mammal"
}
# ここにコードを記述してください
# これより下の行は変更しないでください
print("Does 'book' exist in the dictionary?", find_meaning("book"))
print("Does 'cat' exist in the dictionary?", find_meaning("cat"))
print("Does 'dog' exist in the dictionary?", find_meaning("dog"))