Determine whether the key in the python dictionary exists



There are generally two general approaches:

The first method : use the built-in function implementation:

there is a has_key() method in the attribute method of python's dictionary:

  1. #generate a dictionary
  2. d = {'name':Tom, 'age':10, 'Tel':110}
  3. # print return value
  4. print d.has_key('name')
  5. #result returns True


The second method : use the in method:

  1. #generate a dictionary
  2. d = {'name':Tom, 'age':10, 'Tel':110}
  3. #Print the return value, where d.keys() is to list all the keys of the dictionary
  4. print ‘name’ in d.keys()
  5. print 'name' in d
  6. # Both results return True

In addition to using in, you can also use not in to determine that the key does not exist. Using in is faster than has_key.



Related: Determine whether the key in the python dictionary exists