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

Python中如何实现字典键值互换并合并重复值?

Solution for Dictionary Inversion with Duplicate Values Handling

Got it, let's work through this dictionary inversion problem together. The goal is to swap keys and values, and group multiple keys into a list when their values are the same. Here's a clear, straightforward implementation:

Step-by-Step Implementation

First, let's fill in the inverse function to meet your requirements:

def inverse(dict1):
    reversed_dict = {}
    # Iterate over each key-value pair in the original dictionary
    for key, value in dict1.items():
        # Check if the value already exists as a key in our reversed dict
        if value in reversed_dict:
            # If yes, append the current key to the existing list
            reversed_dict[value].append(key)
        else:
            # If no, create a new list with the current key as its first element
            reversed_dict[value] = [key]
    return reversed_dict

def main():
    dict1 = {'I': 3, 'love': 3, 'python': 2}
    print(inverse(dict1))
if __name__ == "__main__":
    main()

How It Works

Let's break down the logic so you understand every part:

  • We start with an empty dictionary reversed_dict to store our final result.
  • Using dict1.items() lets us loop through every key-value pair in the input dictionary—this is the standard, readable way to iterate over dictionaries in Python.
  • For each value from the original dict:
    • If the value is already a key in reversed_dict, that means we've seen this value before with another key. We just add the current key to the existing list for that value.
    • If the value isn't in reversed_dict yet, we create a new entry where the key is the original value, and the value is a list containing the original key.

When you run the main function, it will output exactly what you need:

{3: ['I', 'love'], 2: ['python']}

Quick Edge Case Note

This implementation assumes all values in the input dictionary are hashable (like integers, strings, tuples)—since dictionary keys must be hashable. If you had unhashable values (like lists) in the input, this would throw an error, but your problem's input uses integers so we're totally covered.

内容的提问来源于stack exchange,提问作者Tal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:56:56