Python Dictionary - In Method

Membership operator - "in":

  • The in operator called on a dictionary instance tests whether a given key is contained in a dictionary.

  • If the value is present in the sequence it returns True. It returns False otherwise.

 

Example 1:          

# Example Python program that uses
# the membership in operator on a dictionary
environmentDictionary = {'path': '/bin:/opt/bin'}

if 'path' in environmentDictionary:       
    print('Path is set');
else:
    print('Path is not set');

Output:

Path is set

 

Example 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

 


Copyright 2023 © pythontic.com