Method # 1: Using items ()
+ Dictionary Comprehension
These functionality together can solve this problem. We can access all the values with items ()
and the condition can be imposed by understanding the dictionary.
# Python3 code for demonstrations # Filter tuple dictionary by condition # Using items () + dictionary # initializing dictionary test_dict = { ’a’ : ( 6 , 3 ), ’b’ : ( 4 , 8 ), ’ c’ : ( 8 , 4 )} # print the original dictionary print ( "The original dictionary is:" + str (test_dict)) # Filter tuple dictionary by condition # Using items () + dictionary res = {key: val for key, val in test_dict.items () if val [ 0 ]" = 6 and val [ 1 ] " = 4 } # print 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 ()
E This method works in the same way as above, except for using the filter
function instead of dictionary comprehension for compact logic. Only works with Python2.
# Python code to demonstrate how it works # Tuple dictionary filter by condition # Using lambda + filter () # initializing dictionary test_dict = { ’a’ : ( 6 , 3 ), ’b’ : ( 4 , 8 ), ’c’ : ( 8 cod e> , 4 )} # print the original dictionary print ( "The original dictionary is:" + str (test_dict)) # Filter tuple dictionary by condition # Using lambda + filter () res = dict ( filter ( lambda (x, (y, z)): y" = 6 and z " = 4 , test_dict.items ())) # print 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)}