Open In App

Python | Check if tuple exists as dictionary key

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with dictionaries, there is a possibility that it’s keys be in form of tuples. This can be a sub problem to some of web development domain. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using in operator This is the most recommended and Pythonic way to perform this particular task. It checks for particular tuple and returns True in case of it occurs or False if doesn’t. 

Python3




# 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, 5)
 
# 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))


Output

The original dictionary : {(3, 4): 'gfg', 6: 'is', (9, 1): 'best'}
Does tuple exists as dictionary key ? : False

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using get() We can use dictionary’s get(), which searches for key in dictionary and if it doesn’t get it, it returns a None. This can be extended in case of tuple keys as well. 

Python3




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


Output : 

The original dictionary : {(3, 4): 'gfg', (9, 1): 'best', 6: 'is'}
Does tuple exists as dictionary key ? : False

Method #3: Using try-catch

Using try-catch, initializes a dictionary, prints the original dictionary,initializes a target tuple and uses try-catch block to check if the target tuple exists as a key in the dictionary. If it does exist, it sets the variable “res” to True, otherwise it sets it to False. The try-catch block will raise a KeyError when the key is not found in the dictionary, and this KeyError is caught and the variable “res” is not modified so it stays False.

Python3




# Method #3: Using try-catch
 
# 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 try-catch
res = False
try:
    test_dict[tar_tup]
    res = True
except KeyError:
    pass
  
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary : {(3, 4): 'gfg', 6: 'is', (9, 1): 'best'}
Does tuple exists as dictionary key ? : False

This method has a time complexity of O(1) as the try-catch block will only be executed once and the dictionary key access is O(1) operation in average case. The auxiliary space of this method is O(1) as it only uses a single variable “res” to store the result.

Method #4: Using the “in” keyword with dictionary keys()

we use the “in” keyword to check if the “tar_tup” tuple exists in the keys of the “test_dict” dictionary. We assign the resulting boolean value to the “res” variable and print it out. In this case, the tuple (3, 5) does not exist as a key in the dictionary, so the result is False.

Python3




# Python3 code to demonstrate working of
# Check if tuple exists as dictionary key
# using "in" keyword with keys()
 
# 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 "in" keyword with keys()
res = tar_tup in test_dict.keys()
 
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))


Output

The original dictionary : {(3, 4): 'gfg', 6: 'is', (9, 1): 'best'}
Does tuple exists as dictionary key ? : False

Time complexity: O(1) 
Auxiliary Space: O(1)

Method #5: Using the dictionary.items() inbuilt methods :

So we are iterating through the dictionary using test_dict.items() and we are also using in keyword to check whether the tuple tar_tup is there in the dictionary. If it is there we return TRUE else return FALSE.

Python3




# Python3 code to demonstrate working of
# Check if tuple exists as dictionary key
# using "in" keyword with items()
 
# 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 "in" keyword with keys()
res = tar_tup in test_dict.items()
 
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))


Output

The original dictionary : {(3, 4): 'gfg', 6: 'is', (9, 1): 'best'}
Does tuple exists as dictionary key ? : False

Time complexity: O(1) 
Auxiliary Space: O(1) as no extra memory is used

Method #6: Using a list comprehension to check if the tuple is equal to any of the dictionary keys:

Step by step Algorithm:

  1. Create a dictionary test_dict with key-value pairs.
  2. Print the original dictionary.
  3. Create a target tuple tar_tup.
  4. Use any function with a generator expression to check if the tar_tup exists as a key in the dictionary.
  5. Print the result.

Python3




# 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 any and keys
res = any(tar_tup == key for key in test_dict.keys())
 
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))


Output

The original dictionary : {(3, 4): 'gfg', 6: 'is', (9, 1): 'best'}
Does tuple exists as dictionary key ? : False

Time Complexity: O(n), where n is the number of keys in the dictionary, This is because the time complexity of this algorithm depends on the size of the input dictionary and the size of the target tuple.
Auxiliary Space: O(1), This is because it only requires a fixed amount of memory to store the input dictionary and the target tuple, regardless of their sizes.

Method #7: Using a loop to iterate through the dictionary keys and compare them with the target tuple.

Python3




# Python3 code to demonstrate working of
# Check if tuple exists as dictionary key
# using a loop
 
# 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 a loop
res = False
for key in test_dict.keys():
    if type(key) is tuple and key == tar_tup:
        res = True
        break
 
# printing result
print("Does tuple exists as dictionary key ? : " + str(res))


Output

The original dictionary : {(3, 4): 'gfg', 6: 'is', (9, 1): 'best'}
Does tuple exists as dictionary key ? : False

Time complexity: O(1) 
Auxiliary Space: O(1) as no extra memory is used



Last Updated : 01 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads