在早期的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中" )

最低0.47元/天 解锁文章
785

被折叠的 条评论
为什么被折叠?



