You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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_dict to hold our final result, and an empty set seen_pairs to track which reciprocal groups we’ve already added.
  • For each key-value pair in the original dictionary:
    1. 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.
    2. 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.
    3. 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 to cleaned_dict.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:08:13