Open In App

Python – Test if all Values are Same in Dictionary

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

Given a dictionary, test if all its values are the same.

Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 8} 
Output : True 
Explanation : All element values are same, 8. 

Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 9} 
Output : False 
Explanation : All element values not same.

Method #1: Using loop

This is one of the ways in which this task can be performed. In this, we iterate for all the values and compare with value in dictionary, if any one is different, then False is returned.

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
# Using loop
 
# initializing dictionary
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Flag to check if all elements are same
res = True
 
# extracting value to compare
test_val = list(test_dict.values())[0]
 
for ele in test_dict:
    if test_dict[ele] != test_val:
        res = False
        break
 
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(1), as the memory usage does not depend on the size of the input.

Method #2: Using set() + values() + len()

This is yet another way in which this task can be performed. In this, we extract all the values using values() and set() is used to remove duplicates. If length of the extracted set is 1, then all the values are assumed to be similar.

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
# Using set() + values() + len()
 
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : 5, "Best" : 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using set() to remove duplicates and check for values count
res = len(list(set(list(test_dict.values())))) == 1
 
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), as we create a list of values from the dictionary.

Method #3: Using values()+len()+count() methods

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
 
# initializing dictionary
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
x = list(test_dict.values())
res = False
if(x.count(x[0]) == len(x)):
    res = True
 
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : 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 #4: Using values() and len() methods

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
 
# initializing dictionary
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
x = list(test_dict.values())
res = False
if([x[0]]*len(x) == x):
    res = True
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : 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. 

Method #5: Using Counter() function

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
from collections import Counter
# initializing dictionary
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
x = list(test_dict.values())
res = False
freq = Counter(x)
if(len(freq) == 1):
    res = True
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True

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

Method #6: Using all() function

This approach uses the built-in all() function to check if all values in the dictionary are equal to the first value.

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
# Using all() function
 
# initializing dictionary
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# extracting value to compare
test_val = list(test_dict.values())[0]
 
# checking if all values are equal to test_val
res = all(val == test_val for val in test_dict.values())
 
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True

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

Method #7 : Using values()+len()+operator.countOf() methods

Approach

  1. Extract the dictionary values using values() method
  2. Initially set res to False
  3. Check whether the count of first element of values list is equal to length of list
  4. If yes set res to True
  5. Display res

Python3




# Python3 code to demonstrate working of
# Test if all Values are Same in Dictionary
 
# initializing dictionary
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
x = list(test_dict.values())
res = False
import operator
if(operator.countOf(x,x[0]) == len(x)):
    res = True
 
# printing result
print("Are all values similar in dictionary? : " + str(res))


Output

The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True

Time Complexity : O(N)

Auxiliary Space : O(N)

N- no of iterations took for checking the count of first element in list

Method #8 : Using numpy:

Algorithm:

  1. Import the numpy library.
  2. Initialize the dictionary with values.
  3. Convert the values of the dictionary to a list using the values() method and convert it to a numpy array using the np.array() method.
  4. Use the np.unique() method on the numpy array to get unique values.
  5. Get the size of the resulting numpy array using the size attribute.
  6. Check if the size of the unique values is 1.
  7. If the size is 1, set the result to True, else set it to False.
  8. Print the result.

Python3




import numpy as np
test_dict = {"Gfg": 5, "is": 5, "Best": 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = np.unique(list(test_dict.values())).size == 1
print("Are all values similar in dictionary? : " + str(res))
#This code is contributed by Jyothi pinjala.


Output:
The original dictionary is : {'Gfg': 5, 'is': 5, 'Best': 5}
Are all values similar in dictionary? : True

Time complexity: O(nlogn), where n is the number of values in the dictionary. The time complexity is dominated by the np.unique() method, which has a time complexity of O(nlogn).

Space complexity: O(n), where n is the number of values in the dictionary. This is because we create a new list and a new numpy array to store the values of the dictionary.



Previous Article
Next Article

Similar Reads

Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have applications across many domains. Let's discuss c
6 min read
Python program to check whether the values of a dictionary are in same order as in a list
Given a dictionary, test if values are in order with list values. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 10, 11] Output : True Explanation : Values are 4, 10, 11, same as list order. Hence True is returned. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 11, 10] Output : False Explanation : V
6 min read
Python Program to display keys with same values in a dictionary List
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'] Explanation : All Gfg values are 5 and best has
5 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop I
8 min read
Practice Tags :