How to test if a key in a dictionary exists?

Larry Bates lbates at websafe.com
Mon Mar 12 10:18:33 EDT 2007


Frank wrote:
> Hi,
> 
> does anyone know how one can test if, e.g., a dictionary 'name' has a
> key called 'name_key'?
> 
> This would be possible:
> 
> keys_of_names = names.keys()
> L = len(keys_of_names)
> 
> for i in range(L):
> if keys_of_names[i] == name_key:
> print 'found'
> 
> 
> But certainly not efficient. I would expect there is something like:
> 
> name.is_key(name_key)
> 
> I appreciate your help!
> 
> Frank
> 
Others have posted the direct answer but often you are wanting to
do something with the key if it exists and the best method is:

try: names['name_key']+=1
except KeyError:
   #
   # Key doesn't exist, create it, display error, or whatever you want
   # to do if it doesn't exist.
   #

-Larry



More information about the Python-list mailing list