Check if a key exists
Lesson 8 of 14 in Coddy's Dictionary in Python course.
To determine if a specified key is present in a dictionary use the in keyword,
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print("name" in my_dict) # Check if a key exists, outputs True
Challenge
EasyYou're given a dictionary representing a collection of words and their meanings. Your task is to write a function named find_meaning that checks if a given word exists in the dictionary.
Try it yourself
# The dictionary of words and their meanings
word_meanings = {
"apple": "a fruit",
"book": "a written or printed work",
"car": "a motor vehicle with four wheels",
"dog": "a domesticated mammal"
}
# Your code here
# Don't change below this line
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"))
All lessons in Dictionary in Python
2Operations
Create DictionaryAccessing ItemsChange ValuesAdding ItemsRemoving ItemsCheck if a key existsLoop Through a Dictionary