Monday, November 18, 2024
Google search engine
HomeLanguagesPython – Filter odd elements from value lists in dictionary

Python – Filter odd elements from value lists in dictionary

Sometimes, while working with Python dictionaries we can have problem in which we need to perform the removal of odd elements from values list of dictionaries. This can have application in many domains including web development. Lets discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension + dictionary comprehension 

This is brute force one liner in which this task can be performed. In this, we remake new dictionary using dictionary comprehension in which filtering data and iteration in value list is performed using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Remove odd elements from value lists in dictionary
# Using list comprehension + dictionary comprehension
 
# initializing Dictionary
test_dict = {'gfg' : [1, 3, 4, 10], 'is' : [1, 2, 8], 'best' : [4, 3, 7]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Remove odd elements from value lists in dictionary
# Using list comprehension + dictionary comprehension
res = {key: [idx for idx in val if idx % 2]
          for key, val in test_dict.items()}
 
# printing result
print("The filtered values are : " + str(res))


Output : 

The original dictionary is : {‘gfg’: [1, 3, 4, 10], ‘best’: [4, 3, 7], ‘is’: [1, 2, 8]} The filtered values are : {‘gfg’: [1, 3], ‘is’: [1], ‘best’: [3, 7]}

Time complexity: O(nm), where n is the number of key-value pairs in the dictionary, and m is the average length of the value lists. 
Auxiliary space: O(nm), since the new dictionary created by the dictionary comprehension has the same number of key-value pairs as the original dictionary, and each value list may potentially be the same length as the original value lists.

Method #2 : Using dictionary comprehension + filter() + lambda 

This is yet another way to solve this problem. In this, the task performed by list comprehension is done using filter() + lambda. 

Python3




# Python3 code to demonstrate working of
# Remove odd elements from value lists in dictionary
# Using filter() + lambda + dictionary comprehension
 
# initializing Dictionary
test_dict = {'gfg' : [1, 3, 4, 10], 'is' : [1, 2, 8], 'best' : [4, 3, 7]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Remove odd elements from value lists in dictionary
# Using filter() + lambda + dictionary comprehension
res = {key: list(filter(lambda ele: (ele % 2), val))
                  for key, val in test_dict.items()}
 
# printing result
print("The filtered values are : " + str(res))


Output : 

The original dictionary is : {‘gfg’: [1, 3, 4, 10], ‘best’: [4, 3, 7], ‘is’: [1, 2, 8]} The filtered values are : {‘gfg’: [1, 3], ‘is’: [1], ‘best’: [3, 7]}

Time complexity: O(n*m), where n is the number of keys in the dictionary and m is the maximum length of the value list.
Auxiliary Space: O(n*m), where n is the number of keys in the dictionary and m is the maximum length of the value list. This is because the filtered lists are stored in the resulting dictionary.

Method 3: using dictionary comprehension 

Using a dictionary comprehension to iterate over the key-value pairs in the dictionary and apply a list comprehension to filter out the odd elements from the value list. The resulting dictionary with only odd elements is stored in the res variable and printed.

Python3




# initializing dictionary
test_dict = {'gfg': [1, 3, 4, 10], 'is': [1, 2, 8], 'best': [4, 3, 7]}
 
# printing original dictionary
print("The original dictionary is:", test_dict)
 
# removing odd elements from value lists in dictionary
res = {key: [ele for ele in val if ele % 2 != 0] for key, val in test_dict.items()}
 
# printing filtered dictionary
print("The filtered dictionary is:", res)


Output

The original dictionary is: {'gfg': [1, 3, 4, 10], 'is': [1, 2, 8], 'best': [4, 3, 7]}
The filtered dictionary is: {'gfg': [1, 3], 'is': [1], 'best': [3, 7]}

Time complexity: O(n*m), where n is the number of keys in the dictionary and m is the maximum length of the value list.
Auxiliary Space: O(n*m), where n is the number of keys in the dictionary and m is the maximum length of the value list. This is because the filtered lists are stored in the resulting dictionary.

Method #4: Using for loops and if conditionals

Step-by-step approach:

  • Initialize an empty dictionary called res.
  • Loop through each key-value pair in test_dict.
    For each key-value pair, we initialize an empty list for the new values to be added to.
  • Loop through each element in the value list.
  • Use an if statement to check if the element is even (i.e., if the remainder when divided by 2 is 0).
  • If the element is even, we append it to the new values list for the current key.
  • Once we’ve looped through all the elements in the value list, we add the new key-value pair to the res dictionary.
  • Print the res dictionary, which contains the filtered values.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Remove odd elements from value lists in dictionary
# Using list comprehension + dictionary comprehension
 
# initializing Dictionary
test_dict = {'gfg' : [1, 3, 4, 10], 'is' : [1, 2, 8], 'best' : [4, 3, 7]}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# Remove odd elements from value lists in dictionary
# Using list comprehension + dictionary comprehension
res = {key: [idx for idx in val if idx % 2 != 0]
          for key, val in test_dict.items()}
 
# printing result
print("The filtered dictionary is: " + str(res))


Output

The original dictionary is: {'gfg': [1, 3, 4, 10], 'is': [1, 2, 8], 'best': [4, 3, 7]}
The filtered dictionary is: {'gfg': [1, 3], 'is': [1], 'best': [3, 7]}

Time complexity: O(n*m), where n is the number of keys in the dictionary and m is the maximum length of any value list in the dictionary.
Auxiliary space: O(n*m), since we need to store the filtered value lists for each key in the dictionary.

Method #5: Using numpy:

Algorithm:

  1. Create an empty dictionary to store the filtered key-value pairs.
  2. Loop through each key-value pair in the input dictionary.
  3. Convert the value list into a numpy array.
  4. Use boolean indexing to select only the odd elements of the array.
  5. Convert the resulting numpy array back into a list.
  6. Add the filtered key-value pair to the output dictionary.
  7. Return the filtered dictionary

Python3




import numpy as np
test_dict = {'gfg': [1, 3, 4, 10], 'is': [1, 2, 8], 'best': [4, 3, 7]}
# printing original dictionary
print("The original dictionary is:", test_dict)
res = {k: np.array(v)[np.array(v) % 2 != 0].tolist() for k, v in test_dict.items()}
 
# printing filtered dictionary
print("The filtered dictionary is:", res)
#This code is contributed by Rayudu.


Output:
The original dictionary is: {'gfg': [1, 3, 4, 10], 'is': [1, 2, 8], 'best': [4, 3, 7]}
The filtered dictionary is: {'gfg': [1, 3], 'is': [1], 'best': [3, 7]}

Time Complexity: O(m).
Auxiliary Space: O(n*m)

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