字典Python中的数据是一个无序的数据值集合,用于存储数据值(如Map),与其他仅将单个值作为元素的数据类型不同,Dictionary拥有key : value
对。
在Python字典中,如果字典中存在指定的键,则has_key()方法返回true,否则返回false。
用法: dict.has_key(key)
参数:
- key-这是要在字典中搜索的键。
返回值:如果字典中有给定的键,则方法返回true,否则返回false。
范例1:
# Python program to show working
# of has_key() method in Dictionary
# Dictionary with three items
Dictionary1 = { 'A': 'Geeks', 'B': 'For', 'C': 'Geeks' }
# Dictionary to be checked
print("Dictionary to be checked: ")
print(Dictionary1)
# Use of has_key() to check
# for presence of a key in Dictionary
print(Dictionary1.has_key('A'))
print(Dictionary1.has_key('For'))
输出:
Dictionary to be checked: {'A': 'Geeks', 'C': 'Geeks', 'B': 'For'} True False
范例2:
# Python program to show working
# of has_key() method in Dictionary
# Dictionary with three items
Dictionary2 = { 1: 'Welcome', 2: 'To', 3: 'Geeks' }
# Dictionary to be checked
print("Dictionary to be checked: ")
print(Dictionary2)
# Use of has_key() to check
# for presence of a key in Dictionary
print(Dictionary2.has_key(1))
print(Dictionary2.has_key('To'))
输出:
Dictionary to be checked: {1: 'Welcome', 2: 'To', 3: 'Geeks'} True False
相关用法
注:本文由纯净天空筛选整理自Akanksha_Rai大神的英文原创作品 Python | Dictionary has_key()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。