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');
    print('Path is not set');


Path is set


Example 2:

# Example Python program that checks
# the presence of a key in a dictionary
# element

fruitPrices = {"Apples":1.42,

fruit2Lookup = "Grapes";

if fruit2Lookup in fruitPrices:               
    print("Yes, %s are available"%fruit2Lookup);
    print("%s not available"%fruit2Lookup);


Grapes not available


Copyright 2023 ©