在早期的Python2版本中,可以使用
dict.has_key()
方法来判断一个键是否存在于字典中。在Python3中,
dict.has_key()
方法被废弃了,不能再被使用。如果在Python3中尝试使用dict.has_key()
方法会导致AttributeError
异常。那在Python3中要如何判断一个键是否存在于字典中呢?
student = {'name': '小明', 'age': 30, 'gender': 'male'}
if ( student.has_key('name') ):
print( studnet['name'] )
一、使用 in 关键字来判断(推荐)
student = {'name': '小明', 'age': 30, 'gender': 'male'}
if 'name' in student:
print( "键 'name' 存在于字典student中" )
else:
print( "键 'name' 不存在于字典student中" )
if 'grade' in student:
print( "键 'grade' 存在于字典student中" )
else:
print( "键 'grade' 不存在于字典student中" )