Monday, November 18, 2024
Google search engine
HomeLanguagesPython | Find Symmetric Pairs in dictionary

Python | Find Symmetric Pairs in dictionary

Sometimes, while working with Python dictionary, one can have a problem in which one desires to get key-value pairs that are symmetrical, i.e that has key-value pair of same value irrespective of the fact value is a key or value. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using generator + loop This task can be solved in brute force method using loops and generators by yielding at runtime the values of matching key-value pairs. 

Python3




# Python3 code to demonstrate working of
# Find Symmetric Pairs in dictionary
# using generator + loop
 
# generator function to perform 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 original dict
print("The original dict is : " + str(test_dict))
 
# Find Symmetric Pairs in dictionary
# using generator + loop
res = []
for key, val in find_sym_pairs(test_dict):
    temp = (key, val)
    res.append(temp)
 
# printing result
print("The pairs of Symmetric values : " + str(res))


Output

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

  Method #2 : Using list comprehension This task can also be performed as a one-liner using list comprehension as a shortened way of performing loop-based solution. 

Python3




# Python3 code to demonstrate working of
# Find Symmetric Pairs in dictionary
# Using list comprehension
 
# Initializing dict
test_dict = {'a' : 1, 'b' : 2, 'c' : 3, 1 : 'a', 2 : 'b'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
# Find Symmetric Pairs in dictionary
# Using list comprehension
temp = [(key, value) for key, value in test_dict.items()]
res = [(x, y) for (x, y) in temp if (y, x) in temp]
 
# printing 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 #3 : Using filter() and lambda function

Python3




# This code demonstrates how to find symmetric pairs in a dictionary using the filter() and lambda function
 
# Initializing the dictionary
test_dict = {'a' : 1, 'b' : 2, 'c' : 31 : 'a', 2 : 'b'}
 
# Printing the original dictionary
print("The original dict is : " + str(test_dict))
 
# Using the filter() function to filter items that have a key-value pair of same value
# The lambda function checks if the value of the current item is a key in the dictionary and if the key corresponds to the current item's value
temp = filter(lambda x: x[1] in test_dict and test_dict[x[1]] == x[0], test_dict.items())
 
# Converting the filter object to a list
res = list(temp)
 
# Printing the 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')]
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

This code demonstrates how to find symmetric pairs in a dictionary using the filter() and lambda function.

First, the code initializes a dictionary test_dict with some key-value pairs.
Then it prints the original dictionary for reference.

Then, it uses the filter() function to filter the items in the dictionary that have a key-value pair of the same value. The filter() function takes two arguments, the first is a lambda function that returns a Boolean value, and the second is the iterable on which the filter is applied, in this case, the items of the dictionary.

The lambda function checks if the value of the current item is a key in the dictionary and if the key corresponds to the current item’s value. If both conditions are true, the item is considered symmetric and is returned by the filter.

The filter object is then converted to a list, and the result is printed.

The time complexity of this method is O(n), as it iterates through the dictionary once. The Auxiliary space is O(n) as it creates a new list to store the symmetric pairs, the size of this list is equal to the number of symmetric pairs, which can be at most n/2.

Method #4 : Using items()+for loop

Python3




# Initializing the dictionary
test_dict = {'a' : 1, 'b' : 2, 'c' : 31 : 'a', 2 : 'b'}
# Printing the original dictionary
print("The original dict is : " + str(test_dict))
# Using a for loop to check if the value is a key in the dictionary
result = []
for key, value in test_dict.items():
    if value in test_dict and test_dict[value] == key:
        result.append((key, value))
# Printing the result
print("The pairs of Symmetric values : " + str(result))
 
 
#This code is contributed by Jyothi pinjala


Output

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

Time complexity : O(n)

Auxiliary space : O(n)

Method 5 :  use a dictionary comprehension to create a new dictionary that contains only the key-value pairs that are symmetric. 

 step-by-step explanation:

  1. Initialize an empty dictionary to store the symmetric key-value pairs.
  2. Use a dictionary comprehension to iterate through the items of the original dictionary and create a new dictionary that contains only the key-value pairs that are symmetric.
  3. Return the new dictionary.

Python3




# Initializing the dictionary
test_dict = {'a' : 1, 'b' : 2, 'c' : 31 : 'a', 2 : 'b'}
 
# Printing the original dictionary
print("The original dict is : " + str(test_dict))
 
# Using dictionary comprehension to find symmetric pairs
symmetric_dict = {key: value for key, value in test_dict.items() if value in test_dict and test_dict[value] == key}
 
# Converting the symmetric dictionary to a list of tuples
symmetric_pairs = list(symmetric_dict.items())
 
# Printing the result
print("The pairs of Symmetric values : " + str(symmetric_pairs))


Output

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

Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(k), where k is the number of symmetric pairs in the dictionary.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments