Open In App

Python – Check if all values are K in dictionary

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

While working with dictionary, we might come to a problem in which we require to ensure that all the values are K in dictionary. This kind of problem can occur while checking the status of the start or checking for a bug/action that could have occurred. Let’s discuss certain ways in which this task can be performed.

Method #1: Using all() + dictionary comprehension The combination of the above functions can be used to perform the following task. The all function checks for each key and dictionary comprehension checks for the K value. 

Python3




# Python3 code to demonstrate working of
# Test if all values are K in dictionary
# Using all() + dictionary comprehension
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
 
# using all() + dictionary comprehension
# Test if all values are K in dictionary
res = all(x == K for x in test_dict.values())
 
# printing result
print("Does all keys have K value ? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(1), as only a constant amount of extra space is used for variables K and res.

Method #2: Using loop This problem can be solved using brute force strategy using loop and we equate each key with K and return True if all elements match K. 

Python3




# Python3 code to demonstrate working of
# Test if all values are K in dictionary
# Using loop
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
 
# using loop
# Test if all values are K in dictionary
res = True
for key in test_dict:
    if test_dict[key] != K:
        res = False
 
# printing result
print("Does all keys have K value ? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(1), as the amount of auxiliary space used by the program is constant and does not depend on the size of the input.

Method #3 : Using values() and len() method

Python3




# Python3 code to demonstrate working of
# Test if all values are K in dictionary
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
res=False
if(list(test_dict.values())==[K]*len(list(test_dict.values()))):
    res=True
# printing result
print("Does all keys have K value ? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method #4: Using set() and len()

Python3




# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
  
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Initialize K
K = 8
  
# using set() and len()
# Test if all values are K in dictionary
res = len(set(test_dict.values())) == 1 and list(set(test_dict.values()))[0] == K
  
# printing result
print("Does all keys have K value ? : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

Time complexity: O(n), where n is length of the dictionary. 
Auxiliary Space is also O(n)

Method #5: Using collections.counter():

Python3




import collections
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Initialize K
K = 8
# Using collections.Counter()
res = collections.Counter(test_dict.values())[K] == len(test_dict)
# printing result
print("Does all keys have K value ? : " + str(res))
#This code is contributed by pinjala Jyothi.


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

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

Method #6: Using reduce() 

Python3




from functools import reduce
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
 
# using reduce() function
# Test if all values are K in dictionary
res = reduce(lambda x, y: x and y, [val == K for val in test_dict.values()])
 
# printing result
print("Does all keys have K value ? : " + str(res))
#This code is contributed Vinay Pinjala.


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

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

Method #7 : Using count() method

Approach

  1. Check whether count of K in values of dictionary is equal to length of dictionary 
  2. If yes make res equals to True
  3. Display res

Python3




# Python3 code to demonstrate working of
# Test if all values are K in dictionary
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 7}
 
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
res=False
x=list(test_dict.values())
if(x.count(K)==len(x)):
  res=True
# printing result
print("Does all keys have K value ? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 7}
Does all keys have K value ? : False

Time Complexity : O(N)

Auxiliary Space : O(1)

Method #8: Using map() and all() functions

  • Initialize a dictionary named test_dict with key-value pairs.
  • Initialize a variable K with a value that we want to check for in the dictionary.
  • Print the original dictionary.
  • map() function and a lambda function are used to iterate over the dictionary and check if all of them are equal to K.
  • all() function is used to check if the values in the dict are equal to K.

Python3




import collections
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
 
# Using map() and all() functions
res = all(map(lambda x: x == K, test_dict.values()))
 
# Printing result
print("Does all keys have K value? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value? : True

Time Complexity: O(N) where N is the number of key-value pairs in the dictionary.

Auxiliary Space: O(N) where N is the number of key-value pairs in the dictionary. 

Method#9: Using Recursive method.

Here’s the algorithm to test if all values in a dictionary are equal to a given value K:

  1. Initialize a boolean variable res to True.
  2. Loop through all the keys in the dictionary.
  3. If the value corresponding to the key is not equal to K, set res to False.
  4. Return the value of res.

Python3




def all_values_equal_to_K(d, K):
    if not d: # base case - dictionary is empty
        return True
    else:
        key, value = next(iter(d.items())) # get the first key-value pair
        if value == K: # if the value is equal to K
            del d[key] # remove the key-value pair from the dictionary
            return all_values_equal_to_K(d, K) # recursive call with updated dictionary
        else:
            return False # if value is not equal to K, return False
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
res=all_values_equal_to_K(test_dict, 8)
# Printing result
print("Does all keys have K value? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value? : True

The time complexity of this algorithm is O(n), where n is the number of key-value pairs in the dictionary. This is because the algorithm needs to loop through all the key-value pairs in the dictionary once.

The auxiliary space of this algorithm is O(1), because the space used by the algorithm does not depend on the size of the input dictionary. The algorithm only uses a constant amount of space to store the boolean variable res and the loop variable key.

Method #10: Using list comprehension and len() function

In this method, we will create a list of True/False values based on whether each value in the dictionary matches the given value K or not. Then, we will check if the length of this list is equal to the length of the dictionary’s values. If yes, then all the values are K in the dictionary, otherwise, they are not.

Step-by-step approach:Steps:

  • Initialize the dictionary.
  • Print the original dictionary.
  • Initialize the value K.
  • Use list comprehension to create a list of True/False values based on whether each value in the dictionary matches the given value K or not.
  • Check if the length of this list is equal to the length of the dictionary’s values.
  • If yes, then all the values are K in the dictionary, otherwise, they are not.
  • Print the result.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Test if all values are K in dictionary
# Using list comprehension and len() function
 
# Initialize dictionary
test_dict = {'gfg' : 8, 'is' : 8, 'best' : 8}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initialize K
K = 8
 
# Using list comprehension and len() function
# Test if all values are K in dictionary
res = len([True for x in test_dict.values() if x == K]) == len(test_dict.values())
 
# printing result
print("Does all keys have K value ? : " + str(res))


Output

The original dictionary is : {'gfg': 8, 'is': 8, 'best': 8}
Does all keys have K value ? : True

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(n), where n is the number of values in the dictionary.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads