Python中如何实现字典键值互换并合并重复值?
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_dictto 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_dictyet, we create a new entry where the key is the original value, and the value is a list containing the original key.
- If the value is already a key in
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

