Python – Filter dictionary values in heterogeneous dictionary
Last Updated :
09 May, 2024
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 certain ways in which this task can be performed.
Input : test_dict = {‘Gfg’ : 10, ‘for’ : ‘geeks’}
Output : {‘Gfg’: 10, ‘for’: ‘geeks’}
Input : test_dict = {‘Gfg’ : ‘geeks’}
Output : {‘Gfg’: ‘geeks’}
Method #1 : Using type() + dictionary comprehension
The combination of above functions can be used to perform this task. In this, we check for integral type using type() and filter the data in dictionary comprehension.
Step-by-step approach
- Use dictionary comprehension to create a new dictionary res.
- Iterate over the items of test_dict using the items() method.
- For each item, check if the value is not an integer (type(val) != int) or if it is greater than K (val > K).
- If the condition is true, add the key-value pair to the new dictionary res.
- Print the new dictionary res using the print() function.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using type() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if type(val) != int or val > K}
# printing result
print("Values greater than K : " + str(res))
OutputThe original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using isinstance() + dictionary comprehension
The combination of above functions can also be used to solve this problem. In this, we perform this task similar to above, but the difference being that type test is done by isinstance() rather than type().
Python3
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using isinstance() + dictionary comprehension
res = {key : val for key, val in test_dict.items()
if not isinstance(val, int) or val > K}
# printing result
print("Values greater than K : " + str(res))
OutputThe original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(k), where k is the number of items in the resulting dictionary after filtering.
Method 3: Using a for loop and conditional statements:
Step-by-step approach:
- Initialize a dictionary test_dict with some key-value pairs.
- Print the original dictionary using print(“The original dictionary : ” + str(test_dict)).
- Initialize an integer K with value 3.
- Create an empty dictionary res to store the filtered values.
- Loop through the key-value pairs of the dictionary using for key, val in test_dict.items()
- Use a conditional statement to filter the dictionary values. If the value is not an integer or it is greater than K, we add it to the res dictionary using res[key] = val.
- Print the filtered dictionary using print(“Values greater than K : ” + str(res)).
Below is the implementation of the above approach:
Python
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
res = {}
for key, val in test_dict.items():
if type(val) != int or val > K:
res[key] = val
# printing result
print("Values greater than K : " + str(res))
OutputThe original dictionary : {'Gfg': 4, 'is': 2, 'best': 3, 'for': 'geeks'}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
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 a dictionary comprehension with if condition:
Step-by-step approach:
- Initialize a dictionary test_dict with some key-value pairs.
- Initialize a variable K with a value to compare against dictionary values.
- Use dictionary comprehension to filter out the items from the dictionary.
- Loop through each key-value pair in the dictionary and check if the value is either non-integer or greater than K.
- If the value satisfies the condition, add the key-value pair to the result dictionary.
- Return the filtered dictionary.
Below is the implementation of the above approach:
Python
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using dictionary comprehension with if condition
res = {k:v for k, v in test_dict.items() if type(v) != int or v > K}
# printing result
print("Values greater than K : " + str(res))
OutputValues greater than K : {'Gfg': 4, 'for': 'geeks'}
Time complexity: O(n) as it loops through all the items in the dictionary once.
Auxiliary space: O(n) as it creates a new dictionary to store the filtered items.
Method #5: Using filter() function with lambda function
Step-by-step approach:
- Initialize a variable K with a value of 3.
- Use the filter() function to filter the items in the test_dict dictionary using a lambda function. The lambda function checks if an item’s value is not an integer or is greater than K.
- Convert the filtered items into a dictionary using the dict() function.
- Assign the filtered dictionary to a variable named res.
- Print the filtered dictionary using the print() function.
Below is the implementation of the above approach:
Python
# initializing dictionary
test_dict = {'Gfg' : 4, 'is' : 2, 'best' : 3, 'for' : 'geeks'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using filter() function with lambda function
res = dict(filter(lambda item: not(isinstance(item[1], int) and item[1] <= K), test_dict.items()))
# printing result
print("Values greater than K : " + str(res))
OutputThe original dictionary : {'Gfg': 4, 'is': 2, 'best': 3, 'for': 'geeks'}
Values greater than K : {'Gfg': 4, 'for': 'geeks'}
Time Complexity: O(n), where n is the size of the input dictionary
Auxiliary Space: O(n), where n is the size of the input dictionary. This is the space required to store the filtered dictionary.
Similar Reads
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "G
6 min read
Python | Extract filtered Dictionary Values
While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and donât care about keys. This is yet another essential utility and solution to it should be known and discussed. Letâs perform this task through certain methods. Method
4 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python | Filter the negative values from given dictionary
Given a dictionary, the task is to filter all the negative values from given dictionary. Let's discuss few methods to do this task. Method #1: Using dict comprehension Follow the below steps to implement: Initializing a dictionary named ini_dict with some key-value pairs.Print the initial dictionary
6 min read
Python - Print dictionary of list values
In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 min read
Remove Duplicate Dictionaries from Nested Dictionary - Python
We are given a nested dictionary we need to remove the duplicate dictionaries from the nested dictionary. For example we are given a nested dictionary d = {'key1': [{'a': 1}, {'b': 2}, {'a': 1}], 'key2': [{'x': 3}, {'y': 4}]} we need to remove the duplicate dictionary from this dictionary so output
4 min read
Python Get All Values from Nested Dictionary
In this article, we will learn how we can Get all Values from Nested Dictionary in Python Programming. A nested Dictionary in Python is a dictionary that contains another dictionary as its values. Using this, we can create a nested structure where each of the key-value pairs is in the outer dictiona
5 min read
Python - Convert dictionary items to values
Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let
3 min read
Python - Filter dictionaries with ordered values
Given the dictionary list, the task is to write a python program to filter dictionaries with values in increasing order i.e sorted. Examples: Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : 4}] Output : [{'gfg': 2, 'is': 8, 'good':
4 min read
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print
2 min read