How to know key exists in Python?
Import the os module:
JavaScript
x
2
1
import os
2
To get an environment variable:
JavaScript
1
2
1
os.environ.get('Env_var')
2
To set an environment variable:
JavaScript
1
3
1
# Set environment variables
2
os.environ['Env_var'] = 'Some Value'
3
Advertisement
Answer
Check If Key Exists using the Inbuilt method keys()
JavaScript
1
15
15
1
def checkKey(dic, key):
2
if key in dic.keys():
3
print("Present, ", end =" ")
4
print("value =", dic[key])
5
else:
6
print("Not present")
7
8
# Driver Code
9
dic = {'a': 100, 'b':200, 'c':300}
10
key = 'b'
11
checkKey(dic, key)
12
13
key = 'w'
14
checkKey(dic, key)
15
JavaScript
1
4
1
Output:
2
Present, value = 200
3
Not present
4
Check If Key Exists using if and in
JavaScript
1
16
16
1
def checkKey(dic, key):
2
3
if key in dic:
4
print("Present, ", end =" ")
5
print("value =", dic[key])
6
else:
7
print("Not present")
8
9
# Driver Code
10
dic = {'a': 100, 'b':200, 'c':300}
11
key = 'b'
12
checkKey(dic, key)
13
14
key = 'w'
15
checkKey(dic, key)
16
JavaScript
1
4
1
Output:
2
Present, value = 200
3
Not present
4
Check If Key Exists using has_key() method
JavaScript
1
15
15
1
def checkKey(dic, key):
2
3
if dic.has_key(key):
4
print("Present, value =", dic[key])
5
else:
6
print("Not present")
7
8
# Driver Function
9
dic = {'a': 100, 'b':200, 'c':300}
10
key = 'b'
11
checkKey(dic, key)
12
13
key = 'w'
14
checkKey(dic, key)
15
JavaScript
1
4
1
Output:
2
Present, value = 200
3
Not present
4
Check If Key Exists using get()
JavaScript
1
8
1
dic = {'a': 100, 'b':200, 'c':300}
2
3
# cheack if "b" is none or not.
4
if dic.get('b') == None:
5
print("Not Present")
6
else:
7
print("Present")
8
JavaScript
1
3
1
Output:
2
Present
3