Use in keyword with dictionaries #
You can use the keyword in with dictionaries to check if a specific key exists in the dictionary or not.
For example:
my_dict = {"name": "John", "age": 25, "gender": "male"}
print("name" in my_dict) # Output: True
print("country" in my_dict) # Output: False
In the example above, the code "name" in my_dict gives us True, because the dictionary my_dict has the key "dict", while the key "country" does not exist in the dictionary.
Exercise #
- Find out if the key
"price"exists in the dictionaryt_shirtand assign the result to the variablehas_price. - Find out if the key
"gender"exists in the dictionaryt_shirtand assign the result to the variablehas_gender.
Tests #
- Variable
has_priceshould beTrue - Variable
has_gendershould beFalse
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules