Change language

Python | Find symmetric pairs in a dictionary

| | | |

Method # 1: Using a Generator + Loop

This problem can be solved by brute-force using loops and generators by issuing values ​​of matched key-value pairs at runtime.

# Python3 code to demonstrate how it works
# Find symmetric pairs in the dictionary
# using generator + loop

 
# generator function to execute the task

def find_sym_pairs (test_dict):

for key in test_dict.keys ():

val = test_dict.get (key)

 

if test_dict.get (val) = = key:

yield key, val

return  

  
# Initializing dict

test_dict = { ’ a’ : 1 , ’b’ : 2 , ’c’ : 3 1 : ’a’ , 2 : ’b ’ }

  
# printing the original dict

print ( " The original dict is: " + str (test_dict))

 
# Find symmetric pairs in the dictionary
# using generator + loop

res = []

for key, val in find_sym_pairs ( test_dict):

temp = (key, val)

res. append (temp)

 
# print result

print ( "The pairs of Symmetric values:" + str (res))

Output:

 The original dict is: {’a’: 1, 1:’ a’, ’c’: 3,’ b’: 2, 2: ’b’} The pairs of Symmetric values: [(’ a’, 1), (1, ’a’), (’ b’, 2 ), (2, ’b’)] 

Method # 2: Using List Comprehension

This task can also be done in a single line, using a list comprehension as a shorthand way to execute a loop-based solution.

# Python3 code for demonstrations
# Find symmetric pairs in the dictionary
# Using the comprehension list

 
# Initializing dict

test_dict = { ’ a’ : 1 , ’b’ : 2 , ’ c’ : 3 1 : ’a’ , 2 : ’b’ }

  
# printing the original dict

print ( "The original dict is:" + str (test_dict))

 
# Find symmetric pairs in dictionary
# Using the comprehension list

temp = [(key, value) for key, value in test_dict.items ()]

res = [(x, y) for ( x, y) in temp if (y, x) in temp]

 
# print result

print ( "The pairs of Symmetric values:" + str (res))

Output:

 The original dict is: {’a’: 1, 1:’ a’, ’c’: 3,’ b’: 2, 2: ’b’} The pairs of Symmetric values: [(’ a’, 1), (1, ’a’), (’ b’, 2), (2, ’b’)] 

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