0
0
PythonProgramBeginner · 2 min read

Python Program to Find Symmetric Pairs in Dictionary

To find symmetric pairs in a dictionary, check for each key-value pair if the reversed pair (value-key) also exists; use code like [(k, v) for k, v in d.items() if (v, k) in d] to get symmetric pairs.
📋

Examples

Input{(1, 2): 'a', (2, 1): 'b', (3, 4): 'c'}
Output[(1, 2), (2, 1)]
Input{(5, 6): 'x', (6, 5): 'y', (7, 8): 'z', (8, 7): 'w'}
Output[(5, 6), (6, 5), (7, 8), (8, 7)]
Input{(1, 3): 'p', (4, 5): 'q'}
Output[]
🧠

How to Think About It

To find symmetric pairs, look at each pair in the dictionary and see if the reversed pair also exists. For example, if (a, b) is a key, check if (b, a) is also a key. Collect all such pairs as symmetric pairs.
📐

Algorithm

1
Get the dictionary input with pairs as keys.
2
Create an empty list to store symmetric pairs.
3
For each key (a, b) in the dictionary, check if (b, a) is also a key.
4
If yes, add both (a, b) and (b, a) to the result list if not already added.
5
Return the list of symmetric pairs.
💻

Code

python
def find_symmetric_pairs(d):
    result = []
    seen = set()
    for (a, b) in d.keys():
        if (b, a) in d and (b, a) not in seen:
            result.append((a, b))
            result.append((b, a))
            seen.add((a, b))
            seen.add((b, a))
    return result

pairs = {(1, 2): 'a', (2, 1): 'b', (3, 4): 'c'}
print(find_symmetric_pairs(pairs))
Output
[(1, 2), (2, 1)]
🔍

Dry Run

Let's trace the dictionary {(1, 2): 'a', (2, 1): 'b', (3, 4): 'c'} through the code

1

Initialize

result = [], seen = set()

2

Check key (1, 2)

(2, 1) is in dictionary and not in seen, so add (1, 2) and (2, 1) to result and seen

3

Check key (2, 1)

(1, 2) is in dictionary but already in seen, so skip

4

Check key (3, 4)

(4, 3) not in dictionary, so skip

5

Return result

[(1, 2), (2, 1)]

KeyIs Reverse Present?Added to ResultSeen Set
(1, 2)YesYes{(1, 2), (2, 1)}
(2, 1)YesNo{(1, 2), (2, 1)}
(3, 4)NoNo{(1, 2), (2, 1)}
💡

Why This Works

Step 1: Check each pair

We look at each key pair (a, b) in the dictionary to find if its reverse (b, a) exists.

Step 2: Avoid duplicates

We use a set to track pairs already added to avoid repeating symmetric pairs.

Step 3: Collect symmetric pairs

If both (a, b) and (b, a) exist and are not seen, we add them to the result list.

🔄

Alternative Approaches

Using set intersection
python
def find_symmetric_pairs_alt(d):
    keys = set(d.keys())
    symmetric = []
    for a, b in keys:
        if (b, a) in keys and (b, a) != (a, b):
            symmetric.append((a, b))
    return symmetric

pairs = {(1, 2): 'a', (2, 1): 'b', (3, 4): 'c'}
print(find_symmetric_pairs_alt(pairs))
This method returns only one of each symmetric pair, which may be simpler but less complete.
Using list comprehension
python
def find_symmetric_pairs_lc(d):
    keys = set(d.keys())
    return [(a, b) for (a, b) in keys if (b, a) in keys and (a, b) <= (b, a)]

pairs = {(1, 2): 'a', (2, 1): 'b', (3, 4): 'c'}
print(find_symmetric_pairs_lc(pairs))
This approach uses tuple comparison to avoid duplicates and is concise but less explicit.

Complexity: O(n) time, O(n) space

Time Complexity

We check each key once and look up its reverse in the dictionary keys, which is O(1) per lookup, so total O(n).

Space Complexity

We use extra space for the result list and a set to track seen pairs, both up to O(n).

Which Approach is Fastest?

The main approach with a set for seen pairs is efficient and clear; alternatives may be shorter but can miss duplicates or add complexity.

ApproachTimeSpaceBest For
Main approach with seen setO(n)O(n)Complete symmetric pairs without duplicates
Set intersection methodO(n)O(n)Simpler code, returns one of each pair
List comprehension with tuple comparisonO(n)O(n)Concise code, avoids duplicates by ordering
💡
Use a set to track visited pairs to avoid counting symmetric pairs twice.
⚠️
Beginners often forget to check if the reversed pair exists or add duplicates multiple times.