Skip to content
Advertisement

Python key exist or not?

How to know key exists in Python?

Import the os module:

import os

To get an environment variable:

os.environ.get('Env_var')

To set an environment variable:

# Set environment variables
os.environ['Env_var'] = 'Some Value'

Advertisement

Answer

Check If Key Exists using the Inbuilt method keys()

def checkKey(dic, key):
    if key in dic.keys():
        print("Present, ", end =" ")
        print("value =", dic[key])
    else:
        print("Not present")
         
# Driver Code
dic = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dic, key)
 
key = 'w'
checkKey(dic, key)
Output:
Present, value = 200
Not present

Check If Key Exists using if and in

def checkKey(dic, key):
     
    if key in dic:
        print("Present, ", end =" ")
        print("value =", dic[key])
    else:
        print("Not present")
 
# Driver Code
dic = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dic, key)
 
key = 'w'
checkKey(dic, key)
Output:
Present, value = 200
Not present

Check If Key Exists using has_key() method

def checkKey(dic, key):
     
    if dic.has_key(key):
        print("Present, value =", dic[key])
    else:
        print("Not present")
 
# Driver Function
dic = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dic, key)
 
key = 'w'
checkKey(dic, key)
Output:
Present, value = 200
Not present

Check If Key Exists using get()

dic = {'a': 100, 'b':200, 'c':300}
 
# cheack if "b" is none or not.
if dic.get('b') == None:
  print("Not Present")
else:
  print("Present")
Output:
Present
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement