Python – Check if key exists in dictionary

In Python, you can use the in operator to check if a key exists in a dictionary.

test.py

def main():
    fruits = {
        'apple':1,
        'orange':2,
        'banana':3
    }
    
	#if key 'apple' exists in fruits?
    if 'apple' in fruits:
        print(fruits['apple'])
    
if __name__ == '__main__':
    main()

Output


1

P.S Tested with Python 3.4.3

Note
has_key() is deprecated in favor of key in d.

References

  1. Python doc Builtins – Removed. dict.has_key()

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
4 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
YvanOnkar BagalRohanLucas DiasManouchehr Rasouli Recent comment authors
newest oldest most voted
Onkar Bagal
Guest
Onkar Bagal

if ‘apple’ in fruits: is not working…….if ‘apple’ in fruits.keys(): works fine

Yvan
Guest
Yvan

Thanks man!

Rohan
Guest
Rohan

def charCount(str):
result = {}
for char in str:
if not result.get(char):
result[char] = 1
else:
result[char]+=1
print(result)

Lucas Dias
Guest
Lucas Dias

TY!!!!!!!!!!!!!!!

Manouchehr Rasouli
Guest
Manouchehr Rasouli

Thank you mkyoung