如何在Python字典中移除反向重复的键值对?
Hey there! Totally get how frustrating it is to spend days stuck on something, especially when you're still getting the hang of Python—no need to apologize for asking for help at all. Let's break this down for you.
Your goal is to take a dictionary with reciprocal key-value pairs (like '27': 28 and '28': 27) and keep only one pair from each reciprocal group. Here's a straightforward approach that works perfectly for your case:
Solution Code
original_dict = {'27': 28, '28': 27, '30': 31, '31': 30} cleaned_dict = {} seen_pairs = set() for key, value in original_dict.items(): # Convert the string key to an integer to match the value's type key_as_int = int(key) # Create a sorted tuple of the pair—this makes reciprocal pairs identical normalized_pair = tuple(sorted((key_as_int, value))) if normalized_pair not in seen_pairs: seen_pairs.add(normalized_pair) cleaned_dict[key] = value print(cleaned_dict) # Output: {'27': 28, '30': 31}
How This Works
Let’s walk through each step so you understand what’s happening:
- We start with your original dictionary, an empty
cleaned_dictto hold our final result, and an empty setseen_pairsto track which reciprocal groups we’ve already added. - For each key-value pair in the original dictionary:
- We convert the string key (like
'27') to an integer to match the value’s type—this avoids errors when sorting, since Python 3 won’t let you compare strings and integers directly. - We create a sorted tuple of the key-value pair. This magic step turns reciprocal pairs into the same tuple:
(27, 28)and(28, 27)both become(27, 28)when sorted. - If this normalized tuple isn’t in
seen_pairs, we add it to the set (so we don’t process the reciprocal pair later) and add the original key-value pair tocleaned_dict.
- We convert the string key (like
- The result is exactly what you want: only one pair from each reciprocal group, keeping the first occurrence from your original dictionary.
Quick Note
If you ever wanted to keep the last occurrence of each reciprocal pair instead, you could reverse the order of iteration (like for key, value in reversed(original_dict.items())), but the above code keeps the first one which matches your example.
Hope this solves your problem—happy coding!
内容的提问来源于stack exchange,提问作者Failure Routine

