📜  Python|字典 has_key()

📅  最后修改于: 2022-05-13 01:54:19.788000             🧑  作者: Mango

Python|字典 has_key()

Python中的Dictionary是数据值的无序集合,用于像 map 一样存储数据值,与其他只保存单个值作为元素的 Data Types 不同,Dictionary 保存key: value对。

注意: has_key()方法在Python 3 中被删除。改用in运算符。

在Python字典中,如果字典中存在指定的键,则has_key()方法返回 true,否则返回 false。

示例 #1:

Python
# 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'))


Python
# 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'))


Python3
# Python Program to search a key in Dictionary
# Using in operator
 
dictionary = {1: "Geeks", 2: "For", 3: "Geeks"}
 
print("Dictionary: {}".format(dictionary))
 
# Return True if Present.
if 1 in dictionary: # or "dictionary.keys()"
    print(dictionary[1])
else:
    print("{} is Absent".format(1))
 
 
# Return False if not Present.
if 5 in dictionary.keys():
    print(dictionary[5])
else:
    print("{} is Absent".format(5))


输出:

Dictionary to be checked: 
{'A': 'Geeks', 'C': 'Geeks', 'B': 'For'}
True
False

示例 #2:

Python

# 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

注意: dict.has_key() 已从Python 3.x 中删除

has_key() 在Python 3 中已被删除。 in运算符用于检查字典中是否存在指定的键。

例子:

Python3

# Python Program to search a key in Dictionary
# Using in operator
 
dictionary = {1: "Geeks", 2: "For", 3: "Geeks"}
 
print("Dictionary: {}".format(dictionary))
 
# Return True if Present.
if 1 in dictionary: # or "dictionary.keys()"
    print(dictionary[1])
else:
    print("{} is Absent".format(1))
 
 
# Return False if not Present.
if 5 in dictionary.keys():
    print(dictionary[5])
else:
    print("{} is Absent".format(5))

输出:

Dictionary: {1:"Geeks",2:"For",3:"Geeks"}
Geeks
5 is Absent