Membership operator - "in"
- The in operator called on a dictionary instance tests whether a given key is present in a dictionary.
- If the value is present in the sequence it returns True. It returns False otherwise.
- The behaviour of in operator is the opposite of the not in operator.
Example 1
# Example Python program that finds
# whether an element is present in a dictionary
# using the "in" operator
d1 = {"if":1, "else":2, "for":3, "while":4}
token = "switch"
if token in d1:
print("Token with value \"%s\" is found"%token)
else:
print("Token with value \"%s\" is not found"%token)Output
Token with value "switch" is not foundExample 2
# Example Python program that checks
# the presence of a key in a dictionary
# element
fruitPrices = {"Apples":1.42,
"Oranges":1.33,
"Kiwi":2.54,
"Avocados":6.1,
"Strawberries":1.7};
fruit2Lookup = "Grapes";
if fruit2Lookup in fruitPrices:
print("Yes, %s are available"%fruit2Lookup);
else:
print("%s not available"%fruit2Lookup);Output
Grapes not available