检查键是否存在
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"))
Python 字典中的所有课
自己练习: Python 在线编译器