b>j)΄!Pԫ&;"kB޶}pSVT(wę!j x;-m@JnQ+պכ7MajfJͱ4jѲ撆RxZMz7vIW/dٞТזcZM~ji ߒsQzԠDW3Den"M+/B:-uIJ7j委9p='mANޭ=/B:-n&nUfqxZM~c Ϲ+,&ᾺܢF[(1*" ϒ"Jԧ<;b" "jܢF[x ,!q қ*]/؝27SMcs"ޭDQ/应ܢF_! :s" 7`F+SVTn"IJnQ/应B 4 wD"IJ׭-`S9DrjiEJ߅gJ应矁[xZM~n"IB؃!'Тѕ+(mIKʭ/|ϐܢF[xZMzG %嬩/c[[ Python - Check if key exists in dictionary - Mkyong.com

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()

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Rohan
7 years ago

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

Lucas Dias
8 years ago

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

Pheeraphat Junsri
5 years ago

easy solution

Manouchehr Rasouli
8 years ago

Thank you mkyoung

Onkar Bagal
7 years ago

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

Yvan
7 years ago
Reply to  Onkar Bagal

Thanks man!