Python | Least Value test in Dictionary
Last Updated : 21 Apr, 2023
While working with dictionary, we might come to a problem in which we require to ensure that all the values are atleast K in dictionary. This kind of problem can occur while checking status of 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 above functions can be used to perform the following task. The all function checks for each key and dictionary comprehension checks for the atleast K value.
Python3 # Python3 code to demonstrate working of # Least Value test in Dictionary # Using all() + dictionary comprehension # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is : " + str(test_dict)) # Initialize K K = 8 # using all() + dictionary comprehension # Least Value test in Dictionary res = all(x >= K for x in test_dict.values()) # printing result print("Does all keys have atleast K value ? : " + str(res))
Output : The original dictionary is : {'gfg': 8, 'best': 11, 'is': 10} Does all keys have atleast K value ? : True
Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(1).
Method #2 : Using loop This problem can be solved using brute force strategy using loop and we compare each key with K and return True if all elements are atleast K.
Python3 # Python3 code to demonstrate working of # Least Value test in Dictionary # Using loop # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is : " + str(test_dict)) # Initialize K K = 8 # using loop # Least Value test in Dictionary res = True for key in test_dict: if test_dict[key] < K: res = False # printing result print("Does all keys have atleast K value ? : " + str(res))
Output : The original dictionary is : {'gfg': 8, 'best': 11, 'is': 10} Does all keys have atleast K value ? : True
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(1), as the space used by the variables does not depend on the size of the dictionary.
Method #3 : Using min()
This problem can also be solved by using the min() function which takes dictionary values as argument and returns the least value.
Python3 # Python3 code to demonstrate working of # Least Value test in Dictionary # Using min() # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is : " + str(test_dict)) # Initialize K K = 8 # using min() # Least Value test in Dictionary res = min(test_dict.values()) >= K # printing result print("Does all keys have atleast K value ? : " + str(res)) #This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary is : {'gfg': 8, 'is': 10, 'best': 11} Does all keys have atleast K value ? : True
Time complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using filter() and len()
Use the filter() function to create a new dictionary containing only the key-value pairs where the value is less than K. This filtered dictionary is then checked to see if its length is zero, which would indicate that all the values in the original dictionary are greater than or equal to K.
Python3 # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is : " + str(test_dict)) # Initialize K K = 8 # using filter() and len() # Least Value test in Dictionary filtered_dict = dict(filter(lambda elem: elem[1] < K, test_dict.items())) res = len(filtered_dict) == 0 # printing result print("Does all keys have atleast K value ? : " + str(res))
OutputThe original dictionary is : {'gfg': 8, 'is': 10, 'best': 11} Does all keys have atleast K value ? : True
Time Complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(m), where m is the number of key-value pairs in the filtered dictionary.
Method #5: Using set() and comparison
- Convert the values of the dictionary into a set.
- Check if K is less than or equal to the minimum value in the set.
- If it is, then all keys have at least K value
Python3 # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is : " + str(test_dict)) # Initialize K K = 8 # using set() and comparison # Least Value test in Dictionary value_set = set(test_dict.values()) res = K <= min(value_set) # printing result print("Does all keys have atleast K value ? : " + str(res))
OutputThe original dictionary is : {'gfg': 8, 'is': 10, 'best': 11} Does all keys have atleast K value ? : True
Time complexity: O(n)
Auxiliary space: O(n)
Method #6: Using Numpy"
Step-by-step approach:
- First, the numpy library is imported with the alias "np". This library is used later in the program to perform an array operation.
- The program initializes a dictionary called "test_dict" with three key-value pairs. The keys are strings and the values are integers.
- The original dictionary is printed using the "print()" function.
- The program initializes a variable called "K" with the value 8.
- Next, the program creates a numpy array called "values_array" containing the values from the dictionary. It does this by using the "values()" function to get a list of the dictionary's values, then passing that list to the "np.array()" function to create a numpy array.
- The program then uses numpy's "all()" function to test if all the values in the "values_array" are greater than or equal to the value of "K". If all values are greater than or equal to "K", then the function returns True. Otherwise, it returns False.
- Finally, the program prints the result of the test as a string using the "print()" function.
- So, the program's overall goal is to check if all the values in the dictionary
Below is the implementation of the above approach:
Python3 import numpy as np # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is: " + str(test_dict)) # Initialize K K = 8 # using numpy library # Least Value test in Dictionary values_array = np.array(list(test_dict.values())) res = np.all(values_array >= K) # printing result print("Does all keys have atleast K value? : " + str(res))
Output
The original dictionary is : {'gfg': 8, 'is': 10, 'best': 11} Does all keys have atleast K value ? : True
Time complexity: O(n) where n is the number of values in the dictionary.
Auxiliary space: O(n) for the numpy array.
Method #7: Using reduce():
Algorithm:
- Initialize the dictionary and K value.
- Apply filter and len functions on the dictionary items to filter out the dictionary keys with values less than K.
- Check if the length of the resulting dictionary is equal to zero or not.
- Print the result.
Python3 from functools import reduce # Initialize dictionary test_dict = {'gfg' : 8, 'is' : 10, 'best' : 11} # Printing original dictionary print("The original dictionary is : " + str(test_dict)) # Initialize K K = 8 # using reduce() and lambda function # Least Value test in Dictionary res = reduce(lambda x, y: x and y, map(lambda val: val >= K, test_dict.values())) # printing result print("Does all keys have atleast K value ? : " + str(res)) #This code is contributed by Vinay pinjala.
OutputThe original dictionary is : {'gfg': 8, 'is': 10, 'best': 11} Does all keys have atleast K value ? : True
Time Complexity: O(n), where n is the number of key-value pairs in the dictionary. This is because filter and len functions take O(n) time to execute.
Space Complexity: O(1). The space used in this code is constant as no extra data structure is used.
Similar Reads
Python - Test Kth index in Dictionary value list
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if, throughout the dictionary, the kth index of all values in the dictionary is equal to N. This kind of problem can occur in the web development domain. Let's discuss certain ways in which this problem
9 min read
Python | N largest values in dictionary
Many times while working with a Python dictionary, we can have a particular problem finding the N maxima of values in numerous keys. This problem is quite common while working in the web development domain. Let's discuss several ways in which this task can be performed. Method #1 : itemgetter() + it
5 min read
Python - Smallest K values in Dictionary
Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Letâs discuss several ways in which this task can be performed. Smallest K values in Dictionary u
4 min read
Python - Test for Empty Dictionary Value List
Given a dictionary with list as values, check if all lists are empty. Input : {"Gfg" : [], "Best" : []} Output : True Explanation : Both lists have no elements, hence True. Input : {"Gfg" : [], "Best" : [4]} Output : False Explanation : "Best" contains element, Hence False. Method #1 : Using any() +
6 min read
Second largest value in a Python Dictionary
In this problem, we will find the second-largest value in the given dictionary. Examples: Input : {'one':5, 'two':1, 'three':6, 'four':10} Output : Second largest value of the dictionary is 6 Input : {1: 'Geeks', 'name': 'For', 3: 'Geeks'} Output : Second largest value of the dictionary is Geeks C/C
2 min read
Sort a Nested Dictionary by Value in Python
Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 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 - Sort List by Dictionary values
Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
3 min read
Python - Value length dictionary
Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
4 min read
Python | Sort dictionary by value list length
While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
4 min read