Possible Duplicate:
'has_key()' or 'in'?
I have a Python dictionary like :
mydict = {'name':'abc','city':'xyz','country','def'}
I want to check if a key is in dictionary or not. I am eager to know that which is more preferable from the following two cases and why?
1> if mydict.has_key('name'): 2> if 'name' in mydict:
Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
Python dictionary doesn't allow key to be repeated.
if 'name' in mydict:
is the preferred, pythonic version. Use of has_key()
is discouraged, and this method has been removed in Python 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With