Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Filter dictionary of tuples by condition

  • Last Updated : 28 Aug, 2019

Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using items() + dictionary comprehension
These functionalities together can achieve this task. We can access all values using items() and condition can be imposed by dictionary comprehension.




# Python3 code to demonstrate working of
# Filter dictionary of tuples by condition
# Using items() + dictionary comprehension
  
# initializing dictionary
test_dict = {'a' : (6, 3), 'b' : (4, 8), 'c' : (8, 4)}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Filter dictionary of tuples by condition
# Using items() + dictionary comprehension
res = {key: val for key, val in test_dict.items() if val[0] >= 6 and val[1] <= 4}
  
# printing result
print("The filtered dictionary is : " +  str(res))
Output :
The original dictionary is : {'b': (4, 8), 'a': (6, 3), 'c': (8, 4)}
The filtered dictionary is : {'a': (6, 3), 'c': (8, 4)}

 

Method #2 : Using lambda + filter()
This method works in similar way as above method with the exception of using the filter function instead of dictionary comprehension to compact logic. Works only with Python2.




# Python code to demonstrate working of
# Filter dictionary of tuples by condition
# Using lambda + filter()
  
# initializing dictionary
test_dict = {'a' : (6, 3), 'b' : (4, 8), 'c' : (8, 4)}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Filter dictionary of tuples by condition
# Using lambda + filter()
res = dict(filter(lambda (x, (y, z)): y >= 6 and z <= 4, test_dict.items()))
  
# printing result
print("The filtered dictionary is : " +  str(res))
Output :
The original dictionary is : {'b': (4, 8), 'a': (6, 3), 'c': (8, 4)}
The filtered dictionary is : {'a': (6, 3), 'c': (8, 4)}

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!