Change language

Python | Filter dictionary of tuples by condition

| |

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 , 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)} 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method