Python|检查元组是否作为字典键存在
有时,在使用字典时,它的键可能是元组的形式。这可能是某些 Web 开发领域的子问题。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用in operator
这是执行此特定任务的最推荐和 Pythonic 方式。它检查特定的元组,如果发生则返回 True,否则返回 False。
# Python3 code to demonstrate working of
# Check if tuple exists as dictionary key
# using in operator
# initialize dictionary
test_dict = { (3, 4) : 'gfg', 6 : 'is', (9, 1) : 'best'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initialize target tuple
tar_tup = (3, 4)
# Check if tuple exists as dictionary key
# using in operator
res = tar_tup in test_dict
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))
输出 :
The original dictionary : {(3, 4): 'gfg', (9, 1): 'best', 6: 'is'}
Does tuple exists as dictionary key ? : True
方法 #2:使用get()
我们可以使用字典的get()
,它在字典中搜索键,如果没有得到它,它返回一个 None。这也可以在元组键的情况下进行扩展。
# Python3 code to demonstrate working of
# Check if tuple exists as dictionary key
# using get()
# initialize dictionary
test_dict = { (3, 4) : 'gfg', 6 : 'is', (9, 1) : 'best'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initialize target tuple
tar_tup = (3, 5)
# Check if tuple exists as dictionary key
# using get()
res = False
res = test_dict.get(tar_tup) != None
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))
输出 :
The original dictionary : {(3, 4): 'gfg', (9, 1): 'best', 6: 'is'}
Does tuple exists as dictionary key ? : False