Python – Filter odd elements from value lists in dictionary
Last Updated :
25 Apr, 2025
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
test_dict = { 'gfg' : [ 1 , 3 , 4 , 10 ], 'is' : [ 1 , 2 , 8 ], 'best' : [ 4 , 3 , 7 ]}
print ("The original dictionary is : " + str (test_dict))
res = {key: [idx for idx in val if idx % 2 ]
for key, val in test_dict.items()}
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
test_dict = { 'gfg' : [ 1 , 3 , 4 , 10 ], 'is' : [ 1 , 2 , 8 ], 'best' : [ 4 , 3 , 7 ]}
print ("The original dictionary is : " + str (test_dict))
res = {key: list ( filter ( lambda ele: (ele % 2 ), val))
for key, val in test_dict.items()}
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
test_dict = { 'gfg' : [ 1 , 3 , 4 , 10 ], 'is' : [ 1 , 2 , 8 ], 'best' : [ 4 , 3 , 7 ]}
print ( "The original dictionary is:" , test_dict)
res = {key: [ele for ele in val if ele % 2 ! = 0 ] for key, val in test_dict.items()}
print ( "The filtered dictionary is:" , res)
|
OutputThe 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
test_dict = { 'gfg' : [ 1 , 3 , 4 , 10 ], 'is' : [ 1 , 2 , 8 ], 'best' : [ 4 , 3 , 7 ]}
print ( "The original dictionary is: " + str (test_dict))
res = {key: [idx for idx in val if idx % 2 ! = 0 ]
for key, val in test_dict.items()}
print ( "The filtered dictionary is: " + str (res))
|
OutputThe 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:
- Create an empty dictionary to store the filtered key-value pairs.
- Loop through each key-value pair in the input dictionary.
- Convert the value list into a numpy array.
- Use boolean indexing to select only the odd elements of the array.
- Convert the resulting numpy array back into a list.
- Add the filtered key-value pair to the output dictionary.
- Return the filtered dictionary
Python3
import numpy as np
test_dict = { 'gfg' : [ 1 , 3 , 4 , 10 ], 'is' : [ 1 , 2 , 8 ], 'best' : [ 4 , 3 , 7 ]}
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()}
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(m).
Auxiliary Space: O(n*m)
Similar Reads
Python - Extract Kth index elements from Dictionary Value list
Given a dictionary with list as values, extract all the Kth index elements. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7], "is" : [9, 3, 8]}, K = 2 Output : [5, 7, 8] Explanation : The 2nd index elements are 5, 7 and 8 respectively in different keys. Input : {"Gfg" : [4, 7, 5], "Best" : [8, 6, 7],
7 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
Filter List Of Dictionaries in Python
Filtering a list of dictionaries is a fundamental programming task that involves selecting specific elements from a collection of dictionaries based on defined criteria. This process is commonly used for data manipulation and extraction, allowing developers to efficiently work with structured data b
2 min read
Python - Check List elements from Dictionary List
Sometimes, while working with data, we can have a problem in which we need to check for list element presence as a particular key in list of records. This kind of problem can occur in domains in which data are involved like web development and Machine Learning. Lets discuss certain ways in which thi
4 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python | Unique dictionary filter in list
We are given a dictionary in list we need to find unique dictionary. For example, a = [ {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"c": 3}, {"a": 1, "b": 3}] so that output should be [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}, {'c': 3}]. Using set with frozensetUsing set with frozenset, we convert dictionary ite
3 min read
Python - Filter Tuples by Kth element from List
Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read
Remove Elements From a List Based on Condition in Python
In Python, lists are a versatile and widely used data structure. There are often situations where you need to remove elements from a list based on a specific condition. In this article, we will explore five simple and commonly used methods to achieve this task. Remove Elements From A List Based On A
3 min read
Python - Filter dictionaries by values in Kth Key in list
Given a list of dictionaries, the task is to write a Python program to filter dictionaries on basis of elements of Kth key in the list. Examples: Input : test_list = [{"Gfg" : 3, "is" : 5, "best" : 10}, {"Gfg" : 5, "is" : 1, "best" : 1}, {"Gfg" : 8, "is" : 3, "best" : 9}, {"Gfg" : 9, "is" : 9, "best
9 min read
Python Filter List of Dictionaries Based on Key Value
Python, a versatile and powerful programming language, offers multiple ways to manipulate and process data. When working with a list of dictionaries, you may often need to filter the data based on specific key-value pairs. In this article, we will explore three different methods to achieve this task
3 min read