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`)]