How to find symmetric pairs in a Python Dictionary

Hello everyone, in this tutorial, we are going to see how we can find symmetric pairs in a Python Dictionary. suppose we have a dictionary called dict = {‘A’: 1, ‘B’: 2, ‘C’: 3, 2: ‘B’, 1: ‘A’}. Then the symmetric pairs in this dictionary are (‘A’, 1) (1, ‘A) and (‘B’, 2) (2, ‘B’). We will be studying how to find these pairs in a given dictionary in detail in this post as we move further.

We will be doing this in two ways. Let’s study them separately.

Using generators

First, we will solve this problem using a generator. If you don’t know about Python generators, please visit this post: How to use generator in Python with examples.

See the given example code and try to understand what each portion of this code does.

dict = {'A': 1, 'B': 2, 'C': 3, 2: 'B', 1: 'A'}

def generator(dict):
    for key in dict.keys():
        value = dict.get(key)
        if dict.get(value) == key:
            yield key, value
pairs = [] 
for key, value in generator(dict):
    pairs.append((key, value))

print("The given dictionary: ", dict)

print("The symmetric pairs: ", pairs)

Output:

The given dictionary: {'A': 1, 'B': 2, 'C': 3, 2: 'B', 1: 'A'}
The symmetric pairs: [('A', 1), ('B', 2), (2, 'B'), (1, 'A')]

Here, as you can see in the example program, we have used a generator which yields the pair of key and value that are symmetrical. We append it to a list pairs and then print it.

Using List Comprehension

Another way to solve the above problem is list comprehension. We can store the symmetrical pairs using a list comprehension. Have a look at the given code for a better understanding of the program.

dict = {'A': 1, 'B': 2, 'C': 3, 2: 'B', 1: 'A'}

pairs  = [(key, value) for key, value in dict.items() if dict.get(value) == key]

print("The given dictionary: ", dict)

print("The symmetric pairs: ", pairs)

Output:

The given dictionary: {'A': 1, 'B': 2, 'C': 3, 2: 'B', 1: 'A'}
The symmetric pairs: [('A', 1), ('B', 2), (2, 'B'), (1, 'A')]

Thank you.

You can also read: Dictionary in Python

Leave a Reply