Python | Test if key exists in tuple keys dictionary
Last Updated :
12 May, 2023
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
test_dict = {( 4 , 5 ) : '1' , ( 8 , 9 ) : '2' , ( 10 , 11 ) : '3' }
print ( "The original dictionary : " + str (test_dict))
key = 10
res = any (key in sub for sub in test_dict)
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
from itertools import chain
test_dict = {( 4 , 5 ): '1' , ( 8 , 9 ): '2' , ( 10 , 11 ): '3' }
print ( "The original dictionary : " + str (test_dict))
key = 10
res = key in chain.from_iterable(test_dict)
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
test_dict = {( 4 , 5 ): '1' , ( 8 , 9 ): '2' , ( 10 , 11 ): '3' }
print ( "The original dictionary : " + str (test_dict))
key = 10
keys = set (key for sub in test_dict for key in sub)
res = key in keys
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
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
- 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.
- 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.
- Finally, we print the result of the search.
Python3
test_dict = {( 4 , 5 ): '1' , ( 8 , 9 ): '2' , ( 10 , 11 ): '3' }
print ( "The original dictionary : " + str (test_dict))
key = 10
keys = set ()
for sub in test_dict:
for k in sub:
keys.add(k)
res = key in keys
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*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
test_dict = {( 4 , 5 ): '1' , ( 8 , 9 ): '2' , ( 10 , 11 ): '3' }
print ( "The original dictionary : " + str (test_dict))
key = 10
res = key in [k[ 0 ] for k in test_dict.keys()]
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:
- Initialize the input dictionary and the test key.
- Extract the tuple keys from the dictionary and store them as a numpy array.
- Check if the test key is present in the numpy array of tuple keys using np.any and np.sum functions.
- Return True if the test key is present in the numpy array, else return False.
- Print the result.
Python3
import numpy as np
test_dict = {( 4 , 5 ): '1' , ( 8 , 9 ): '2' , ( 10 , 11 ): '3' }
print ( "The original dictionary : " + str (test_dict))
key = 10
keys = np.array([k for k in test_dict.keys()])
res = np. any (np. sum (keys = = key, axis = 1 ))
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 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).
Similar Reads
Check if Tuple Exists as Dictionary Key - Python
The task is to check if a tuple exists as a key in a dictionary. In Python, dictionaries use hash tables which provide an efficient way to check for the presence of a key. The goal is to verify if a given tuple is present as a key in the dictionary. For example, given a dictionary d = {(3, 4): 'gfg'
3 min read
Python - Test if custom keys equal to K in dictionary
Given dictionary and custom keys list, check if all those custom keys equals K. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 10, "Geeks" : 10}, cust_keys = ["is", "for", "Geeks"], K = 10 Output : False Explanation : "is" is having 8 as value not 10, hence False Input : test_dict =
6 min read
Delete a Python Dictionary Item If the Key Exists
We are given a dictionary and our task is to delete a specific key-value pair only if the key exists. For example, if we have a dictionary 'd' with values {'x': 10, 'y': 20, 'z': 30} and we want to remove the key 'y', we should first check if 'y' exists before deleting it. After deletion, the update
3 min read
Python Remove Key from Dictionary if Exists
We are given a dictionary and a key and our task is to remove the key from the dictionary if it exists. For example, d = {"a": 10, "b": 20, "c": 30} and key to remove is "b" then output will be {"a": 10, "c": 30}. Using pop() pop() method allows us to remove a key from a dictionary while specifying
2 min read
Python | Filter Tuple Dictionary Keys
Sometimes, while working with Python dictionaries, we can have itâs keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 min read
Get Total Keys in Dictionary - Python
We are given a dictionary and our task is to count the total number of keys in it. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} then the output will be 4 as the total number of keys in this dictionary is 4. Using len() with dictThe simplest way to count the total num
2 min read
Python | Test if element is dictionary value
Sometimes, while working with a Python dictionary, we have a specific use case in which we just need to find if a particular value is present in the dictionary as it's any key's value. This can have use cases in any field of programming one can think of. Let's discuss certain ways in which this prob
4 min read
Python - Remove Disjoint Tuple Keys from Dictionary
We are given a dictionary we need to remove the Disjoint Tuple key from it. For example we are given a dictionary d = {('a', 'b'): 1, ('c',): 2, ('d', 'e'): 3, 'f': 4} we need to remove all the disjoint tuple so that the output should be { }. We can use multiple methods like dictionary comprehension
3 min read
Python | Test if tuple is distinct
Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is a brute force
4 min read
Get the First Key in Dictionary - Python
We are given a dictionary and our task is to find the first key in the dictionary. Since dictionaries in Python 3.7+ maintain insertion order, the first key is the one that was added first to the dictionary. For example, if we have the dictionary {'a': 10, 'b': 20, 'c': 30}, the first key is 'a'. Us
2 min read