Editor settings

General settings

Save settings

Learn to program with Python

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 dictionary t_shirt and assign the result to the variable has_price.
  • Find out if the key "gender" exists in the dictionary t_shirt and assign the result to the variable has_gender.

Tests #

  • Variable has_price should be True
  • Variable has_gender should be False
Output will be displayed here