Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether a key is present in a dictionary [duplicate]

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: 
like image 202
Avadhesh Avatar asked Sep 17 '10 09:09

Avadhesh


People also ask

How do you check if a key is already present in dictionary?

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.

Can a dictionary key be duplicated?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can keys be duplicate in dictionary Python?

Python dictionary doesn't allow key to be repeated.


1 Answers

if 'name' in mydict: 

is the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.

like image 135
Tim Pietzcker Avatar answered Sep 28 '22 00:09

Tim Pietzcker