Open In App

Python | Test if key exists in tuple keys dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with dictionary data, we need to check if a particular key is present in the dictionary. If keys are elementary, the solution to a problem in discussed and easier to solve. But sometimes, we can have a tuple as key of the dictionary. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using any() + generator expression 

A combination of the above functionalities can be used to perform this task. In this, we check for each element inside each key for the target key. The any() is used to check in any keys of the dictionary. 

Python3




# Python3 code to demonstrate working of
# Test if key exists in tuple keys dictionary
# using any() + generator expression
 
# initialize dictionary
test_dict = {(4, 5) : '1', (8, 9) : '2', (10, 11) : '3'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Test key
key = 10
 
# Test if key exists in tuple keys dictionary
# using any() + generator expression
res = any(key in sub for sub in test_dict)
 
# printing result
print("Does key exists in dictionary? : " + str(res))


Output

The original dictionary : {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
Does key exists in dictionary? : True

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(1), as only constant space, is used for storing the test key and the result.

Method #2: Using from_iterable() 

This task can also be performed using this function. In this, we flatten the keys and then check for existence. 

Python3




# Python3 code to demonstrate working of
# Test if key exists in tuple keys dictionary
# using from_iterable()
from itertools import chain
 
# initialize dictionary
test_dict = {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Custom test key
key = 10
 
# Test if key exists in tuple keys dictionary
# using from_iterable()
res = key in chain.from_iterable(test_dict)
 
# printing result
print("Does key exists in dictionary? : " + str(res))


Output

The original dictionary : {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
Does key exists in dictionary? : True

Method #3 : Using set() + list comprehension

This approach is more efficient than the previous ones as it leverages the fast membership checking of sets. In this method, we convert the keys of the dictionary to a set and then check for the existence of the key using list comprehension.

Python3




# Python3 code to demonstrate working of
# Test if key exists in tuple keys dictionary
# using set() + list comprehension
 
# initialize dictionary
test_dict = {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Custom test key
key = 10
 
# Test if key exists in tuple keys dictionary
# using set() + list comprehension
keys = set(key for sub in test_dict for key in sub)
res = key in keys
 
# printing result
print("Does key exists in dictionary? : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary : {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
Does key exists in dictionary? : True

This approach uses the concept of set, which stores only unique elements, and list comprehension to iterate over the tuple keys, and extract all the elements inside the tuple and store it as a set. Then it checks if the target key is present in the set. 

Time complexity: O(n) where n is the number of keys in the dictionary since we are iterating over all the keys in the dictionary to form the set. 
Auxiliary Space: O(n) as well since we are storing all the elements of tuple keys in a set.

Method#4: Using a for loop

  1. We first initialize an empty set called keys. We then use a nested for loop to iterate over each tuple in the dictionary and each element within those tuples. For each element k, we add it to the keys set.
  2. After we’ve collected all the unique keys in the dictionary, we check if our key variable is present in the keys set, and store the result in the res variable.
  3. Finally, we print the result of the search.

Python3




# initialize dictionary
test_dict = {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Test key
key = 10
 
# Test if key exists in tuple keys dictionary
keys = set()
 
for sub in test_dict:
    for k in sub:
        keys.add(k)
 
res = key in keys
 
# printing result
print("Does key exists in dictionary? : " + str(res))
 
# This code is contributed by Vinay Pinjala.


Output

The original dictionary : {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
Does key exists in dictionary? : True

Time complexity: O(n*m), where n is the number of tuples in the dictionary, and m is the maximum number of elements in any of those tuples. This is because we need to iterate over each element of each tuple in the dictionary to collect all the unique keys.

Auxiliary Space: O(N*M), because we need to store each unique key in the keys set. The size of the set will depend on the number of unique keys in the dictionary, which could be up to n*m in the worst case if every element in every tuple is unique.

Method 5:  Using “in” keyword with dictionary.keys() method

Python3




# Python3 code to demonstrate working of
# Test if key exists in tuple keys dictionary
# using "in" keyword with dictionary.keys() method
 
# Initialize dictionary
test_dict = {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
 
# Printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Test key
key = 10
 
# Testing if key exists in tuple keys dictionary
# using "in" keyword with dictionary.keys() method
res = key in [k[0] for k in test_dict.keys()]
 
# Printing result
print("Does key exists in dictionary? : " + str(res))


Output

The original dictionary : {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
Does key exists in dictionary? : True

Time Complexity: O(n), The list comprehension extracts the first element of each key, which takes O(n) time where n is the number of keys in the dictionary.
Auxiliary Space: O(n), The list comprehension creates a list of size n, where n is the number of keys in the dictionary.

Method 6:  Using numpy:

  1. Initialize the input dictionary and the test key.
  2. Extract the tuple keys from the dictionary and store them as a numpy array.
  3. Check if the test key is present in the numpy array of tuple keys using np.any and np.sum functions.
  4. Return True if the test key is present in the numpy array, else return False.
  5. Print the result.

Python3




import numpy as np
 
# initialize dictionary
test_dict = {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Test key
key = 10
 
# Test if key exists in tuple keys dictionary
keys = np.array([k for k in test_dict.keys()])
res = np.any(np.sum(keys == key, axis=1))
 
# printing result
print("Does key exists in dictionary? : " + str(res))
#This code is contributed by Jyothi pinjala


Output:
The original dictionary : {(4, 5): '1', (8, 9): '2', (10, 11): '3'}
Does key exists in dictionary? : True

Time complexity:  O(N) where N is the size of the dictionary. The time complexity for checking if the key is present in the numpy array using np.any and np.sum functions is O(M) where M is the size of the numpy array. The total time complexity of the algorithm is O(N + M).

Auxiliary Space: O(N) where N is the size of the dictionary. The space complexity for storing the test key and other variables is O(1). The total space complexity of the algorithm is O(N).



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