Python - Test if custom keys equal to K in dictionary
Last Updated :
05 Apr, 2023
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 = {"Gfg" : 5, "is" : 10, "Best" : 10, "for" : 10, "Geeks" : 10}, cust_keys = ["is", "for", "Geeks"], K = 10
Output : True
Explanation : All keys have 10 as values.
Method #1 : Using loop
This is brute way in which this task can be performed. In this we iterate each custom key and check if all are equal to K by keeping track using boolean variable.
Python3
# Python3 code to demonstrate working of
# Test if custom keys equal to K in dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# using loop to check for all keys
res = True
for key in cust_keys:
if test_dict[key] != K:
# break even if 1 value is not equal to K
res = False
break
# printing result
print("Are all custom keys equal to K : " + str(res))
OutputThe original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True
Method #2 : Using all() + generator expression
The combination of above functionalities can be used to solve this problem. In this, we use all() to check for all the values and generator expression performs required iteration.
Python3
# Python3 code to demonstrate working of
# Test if custom keys equal to K in dictionary
# Using all() + generator expression
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# returns true if all elements match K
res = all(test_dict[key] == K for key in cust_keys)
# printing result
print("Are all custom keys equal to K : " + str(res))
OutputThe original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True
Method #3: Using Set intersection to check if all the custom keys in the dictionary have the value K
Step-by-step algorithm:
- Create a set of intersection of cust_keys and test_dict keys.
- Check if the intersection set is equal to the set of cust_keys.
- If the intersection set is not equal to the set of cust_keys, return False.
- If the intersection set is equal to the set of cust_keys, iterate over each key in cust_keys.
- Check if the value of the key in test_dict is equal to K.
- If the value of the key in test_dict is not equal to K, return False.
- If all the values in test_dict for the custom keys are equal to K, return True.
Python3
# initialize a dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# initialize custom keys and K value
cust_keys = ["is", "for", "Geeks"]
K = 8
# print the original dictionary
print("The original dictionary is : " + str(test_dict))
# check if all custom keys are present in the dictionary and have value equal to K
res = set(cust_keys).intersection(test_dict.keys()) == set(cust_keys) and all(test_dict[key] == K for key in cust_keys)
# print the result
print("Are all custom keys equal to K : " + str(res))
OutputThe original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True
Complexity Analysis:
Time Complexity: O(n), where n is the length of the cust_keys list.
Auxiliary Space: O(m), where m is the number of keys in the test_dict dictionary.
Method #4: Using the filter() function and a lambda function:
- Initialize the integer variable K with the value to be compared.
- Define a lambda function that takes a key and checks if the value corresponding to the key in the dictionary is equal to K.
- Use the filter() function with the defined lambda function and the list of custom keys cust_keys to filter out the keys whose values are not equal to K.
- Convert the filtered result obtained in step 6 to a list and check if its length is equal to the length of the list cust_keys. If the lengths are equal, it means all the custom keys have values equal to K, so set res to True.
- Otherwise, set res to False.
- Print the result.
Python3
# Python3 code to demonstrate working of
# Test if custom keys equal to K in dictionary
# Using filter() + lambda
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# using filter() and lambda function to check for all keys
res = all(filter(lambda x: test_dict[x] == K, cust_keys))
# printing result
print("Are all custom keys equal to K : " + str(res))
OutputThe original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True
Time Complexity: O(m), where m is the number of keys in the test_dict dictionary.
Auxiliary Space: O(1), as no extra space is required.
Method #5 : Using count() and len() methods:
Approach:
- Create an empty list x.
- Initiate a for loop to append the values of custom keys to a list x.
- Check whether the count of K in x is equal to the length of x(using count()). If yes, then print "Are all custom keys equal to K: True", Otherwise, print "Are all custom keys equal to K: False".
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of test
# if custom keys equal to K in dictionary
# Using loop
# initializing dictionary
test_dict = {"Gfg": 5, "is": 8, "Best": 10, "for": 8, "Geeks": 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing custom keys list
cust_keys = ["is", "for", "Geeks"]
# initializing K
K = 8
# using loop to check for all keys
x = []
for i in cust_keys:
x.append(test_dict[i])
res = x.count(K) == len(x)
# printing result
print("Are all custom keys equal to K : " + str(res))
OutputThe original dictionary is : {'Gfg': 5, 'is': 8, 'Best': 10, 'for': 8, 'Geeks': 8}
Are all custom keys equal to K : True
Time Complexity: O(N) N - length of cust_keys
Auxiliary Space: O(1)
Similar Reads
Python | Test if key exists in tuple keys dictionary
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
7 min read
Python - Custom Tuple Key Summation in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let'
7 min read
Remove Dictionary from List If Key is Equal to Value in Python
Removing dictionaries from a list based on a specific condition is a common task in Python, especially when working with data in list-of-dictionaries format. In this article, we will see various methods to Remove Dictionary from List If the Key is Equal to the Value in Python.Using filter()filter()
2 min read
Python - Count if dictionary position equals key or value
Given a dictionary, count instances where dictionary item position equals key or value. Valid for Py >= 3.6 [ Introduction of dictionary ordering ]. Input : test_dict = {5:3, 2:3, 10:4, 7:3, 8:1, 9:5} Output : 2 Explanation : At 3 and 5th position, values are 3 and 5. Input : test_dict = {5:3, 2:
3 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 numb
2 min read
Python - Summation of Custom nested keys in Dictionary
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary. Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1] Output : 18 Explanation : 6 + 9 + 3 = 18, only
10 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 - Dictionary Keys whose Values summation equals K
Given a dictionary and a value K, extract keys whose summation of values equals K. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}, K = 17 Output : ['Best', 'for'] Explanation : 9 + 8 = 17, hence those keys are extracted. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks
9 min read
Python - Resolve Float Keys in Dictionary
Given a dictionary with variety of floating-point keys, find a way to access them as single value. Input : test_dict = {"010.78" : "Gfg", "9.0" : "is", "10" : "Best"}, K = "09.0" Output : "is" Explanation : 09.0 -> 9.0 whose value is "is". Input : test_dict = {"010.78" : "Gfg", "9.0" : "is", "10"
5 min read
Python - Initialize dictionary with custom value list
In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with a custom list.
4 min read