Monday, November 18, 2024
Google search engine
HomeLanguagesPython – Test for Even values dictionary values lists

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, 16, 14, 6]} 
Output : {‘Gfg’: False, ‘is’: False, ‘Best’: True} 
Explanation : Only “Best” has even numbers.

Method #1: Using loop

This is brute way in which this task can be performed. In this, we iterate for all the values and check if all list values are Even if yes, we assign key as True else False.

Python3




# Python3 code to demonstrate working of
# Test for Even values dictionary values lists
# Using loop
 
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
             "is" :  [8, 10, 12, 16],
             "Best" : [10, 16, 14, 6]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
res = dict()
for sub in test_dict:
    flag = 1
     
    # checking for even elements
    for ele in test_dict[sub]:
        if ele % 2 != 0:
            flag = 0
            break
    # adding True if all Even elements
    res[sub] = True if flag else False
 
# printing result
print("The computed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}

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

Method #2:  Using all() + dictionary comprehension

This is yet another way in which this task can be performed. In this, we check for all the elements using all() and dictionary comprehension is used to remake the result.

Python3




# Python3 code to demonstrate working of
# Test for Even values dictionary values lists
# Using all() + dictionary comprehension
 
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
             "is" :  [8, 10, 12, 16],
             "Best" : [10, 16, 14, 6]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using all to check for all even elements
res = {sub : all(ele % 2 == 0 for ele in test_dict[sub]) for sub in test_dict}
 
# printing result
print("The computed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}

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

Method #3:  Using items()+filter()+ lambda functions

Python3




# Python3 code to demonstrate working of
# Test for Even values dictionary values lists
 
# initializing dictionary
test_dict = {"Gfg": [6, 7, 3],
             "is":  [8, 10, 12, 16],
             "Best": [10, 16, 14, 6]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
res = []
# using all to check for all even elements
for key, value in test_dict.items():
    evenValues = list(filter(lambda x: x % 2 == 0, value))
    if(len(evenValues) == len(value)):
        res.append(key)
# printing result
print("The computed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : ['is', 'Best']

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

Method #4: Using NumPy library

Python3




import numpy as np
 
# Test for Even values dictionary values lists
# Using numpy library
 
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
             "is" :  [8, 10, 12, 16],
             "Best" : [10, 16, 14, 6]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using numpy library
res = {key: np.all(np.mod(test_dict[key], 2) == 0) for key in test_dict}
 
# printing result
print("The computed dictionary : " + str(res))
 
#This code is contributed by Vinay Pinjala.


Output:

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}

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

Method #5: Using reduce() and map() functions:

Step-by-step approach:

  • Import the “reduce” function from the “functools” library.
  • Initialize an empty list called “res” to store the keys of the dictionary whose values are all even.
  • Initialize the input dictionary called “test_dict”.
  • Iterate through the items of the dictionary using the “items()” method.
  • Use the “reduce()” and “map()” functions to check if all the values in the current key’s value list are even.
  • If all the values are even, append the key to the “res” list.
  • Print the final result.

Below is the implementation of the above approach:

Python3




# import the reduce function from the functools library
from functools import reduce
# initialize the list `res` to store the keys of the dictionary whose values are all even
res = []
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
             "is" :  [8, 10, 12, 16],
             "Best" : [10, 16, 14, 6]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# iterate through the items of the dictionary `test_dict`
for key, value in test_dict.items():
    # use `reduce` and `map` to check if all the values in the `value` list are even
    evenValues = reduce(lambda a, b: a and b, map(lambda x: x % 2 == 0, value))
    # if all the values are even, append the key to the `res` list
    if evenValues:
        res.append(key)
# print the final result
print("The computed dictionary : " + str(res))
#This code is contributed by Jyothi pinjala


Output

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : ['is', 'Best']

Time Complexity:

  • The time complexity of the “reduce()” function is O(n), where n is the number of items in the input list.\The time complexity of the “map()” function is also O(n), where n is the number of items in the input list.
  • Therefore, the time complexity of the algorithm is O(m*n), where m is the number of key-value pairs in the dictionary and n is the length of the longest value list in the dictionary.

Auxiliary Space:

  • The space complexity of the algorithm is O(m), where m is the number of key-value pairs in the dictionary.
  • This is because we are storing the keys of the dictionary whose values are all even in the “res” list, which has a maximum size of m.

Method #6: Using list comprehension and all() function

  • Start by initializing the dictionary test_dict with some key-value pairs.
  • Use a dictionary comprehension to create a new dictionary res by iterating over the key-value pairs in test_dict.
  • For each key-value pair, we use a list comprehension to check if all the elements in the list value are even. We do this by checking if the remainder of each element with 2 is 0, using the modulo operator %.
  • Use the all() function to check if all the elements in the list comprehension are True. If they are, we set the value of the corresponding key in res to True, otherwise we set it to False.
  • Finally, print the original dictionary and the computed dictionary.

Python3




# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
             "is" :  [8, 10, 12, 16],
             "Best" : [10, 16, 14, 6]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using list comprehension and all() function to check if all elements are even
res = {k: all(ele % 2 == 0 for ele in v) for k, v in test_dict.items()}
 
# printing result
print("The computed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}

Time complexity: O(n*m), where n is the number of keys in the dictionary and m is the maximum length of any list value in the dictionary.
Auxiliary space: O(n), where n is the number of keys in the dictionary, to store the result in the dictionary res.

Method #7: Using dictionary comprehension and any() function:

Step-by-step approach:

  • Initialize the dictionary
  • Create a dictionary comprehension that iterates over the key-value pairs of the original dictionary
  • For each key-value pair, use the any() function with a generator expression to check if any of the elements in the value list are odd
  • The result of the any() function will be used as the value for the new dictionary
  • Return the new dictionary

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {"Gfg" : [6, 7, 3],
             "is" :  [8, 10, 12, 16],
             "Best" : [10, 16, 14, 6]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Using dictionary comprehension and any() function to check if any element is odd
res = {k: not any(ele % 2 != 0 for ele in v) for k, v in test_dict.items()}
 
# printing result
print("The computed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 3], 'is': [8, 10, 12, 16], 'Best': [10, 16, 14, 6]}
The computed dictionary : {'Gfg': False, 'is': True, 'Best': True}

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments