Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | N largest values in dictionary
Next article icon

Python | Least Value test in Dictionary

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

Output
The 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)) 

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 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)) 

Output
The 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:

  1. First, the numpy library is imported with the alias "np". This library is used later in the program to perform an array operation.
  2. The program initializes a dictionary called "test_dict" with three key-value pairs. The keys are strings and the values are integers.
  3. The original dictionary is printed using the "print()" function.
  4. The program initializes a variable called "K" with the value 8.
  5. 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.
  6. 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.
  7. Finally, the program prints the result of the test as a string using the "print()" function.
  8. 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:

  1. Initialize the dictionary and K value.
  2. Apply filter and len functions on the dictionary items to filter out the dictionary keys with values less than K.
  3. Check if the length of the resulting dictionary is equal to zero or not.
  4. 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. 

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 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.


Next Article
Python | N largest values in dictionary
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences