Python Program to Find Symmetric Pairs in Dictionary
[(k, v) for k, v in d.items() if (v, k) in d] to get symmetric pairs.Examples
How to Think About It
Algorithm
Code
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))
Dry Run
Let's trace the dictionary {(1, 2): 'a', (2, 1): 'b', (3, 4): 'c'} through the code
Initialize
result = [], seen = set()
Check key (1, 2)
(2, 1) is in dictionary and not in seen, so add (1, 2) and (2, 1) to result and seen
Check key (2, 1)
(1, 2) is in dictionary but already in seen, so skip
Check key (3, 4)
(4, 3) not in dictionary, so skip
Return result
[(1, 2), (2, 1)]
| Key | Is Reverse Present? | Added to Result | Seen Set |
|---|---|---|---|
| (1, 2) | Yes | Yes | {(1, 2), (2, 1)} |
| (2, 1) | Yes | No | {(1, 2), (2, 1)} |
| (3, 4) | No | No | {(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
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))
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))
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Main approach with seen set | O(n) | O(n) | Complete symmetric pairs without duplicates |
| Set intersection method | O(n) | O(n) | Simpler code, returns one of each pair |
| List comprehension with tuple comparison | O(n) | O(n) | Concise code, avoids duplicates by ordering |