Tags
Asked 2 years ago
5 Aug 2021
Views 388
Janice

Janice posted

How do you check if a key exists in a Python dictionary ?

How do you check if a key exists in a Python dictionary ?
Rasi

Rasi
answered Aug 8 '21 00:00

You can use in operator :


index in dictionary variable

Again checking index in the dictionary in Python
example code :

a={"d":'a',"l":'c'}
if("test" in a):
	print("exists")
else:
	print("does not exists")

it will print does not exists becuase given index is not in given dictionary

Again checking index in the dictionary in Python

a={"d":'a',"l":'c'}
if("d" in a):
	print("exists")
else:
	print("does not exists")

it will print exits


ajamil

ajamil
answered Aug 8 '21 00:00

not in operator used to check if key not in exists in a given dictionary or not


c=dict([('foo', 100), ('bar', 200)])
if("foo" not in c):
	print("not exists")
else:
	print("exists")


not in is opposite of the in operator
Post Answer