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

如何按指定格式反转Python字典?解决列表不可哈希报错

Fixing Dictionary Reversal with List Values

Hey there! Let's tackle this dictionary reversal issue you're facing. The error unhashable type: 'list' pops up because you're trying to use lists (from d.values()) as keys in your reversed structure—but dictionary keys need to be hashable (like strings, integers, etc.), and lists aren't hashable. Your current zip approach pairs entire value lists with keys, which isn't what we need here.

The Correct Approach

We need to iterate through each element in the value lists of the original dictionary, then map each of those elements to the original key(s). Here's how to do it:

def reverse_dictionary(d):
    reversed_dict = {}
    # Iterate over each key-value pair in the original dictionary
    for original_key, value_list in d.items():
        # Go through each element in the value list
        for new_key in value_list:
            # If the new key isn't in the reversed dict yet, create an empty list for it
            if new_key not in reversed_dict:
                reversed_dict[new_key] = []
            # Append the original key to the list for this new key
            reversed_dict[new_key].append(original_key)
    return reversed_dict

Testing It Out

Let's use your sample dictionary to verify:

d = {'move': ['liikuttaa'], 'hide': ['piilottaa', 'salata'], 'six': ['kuusi'], 'fir': ['kuusi']}
print(reverse_dictionary(d))

This will output exactly what you want:

{'liikuttaa': ['move'], 'piilottaa': ['hide'], 'salata': ['hide'], 'kuusi': ['six', 'fir']}

Why This Works

  • We use a nested loop: first loop over each original key and its associated list, then loop over each item in that list.
  • For each item (which becomes our new key), we check if it already exists in the reversed dictionary. If not, we initialize an empty list. Then we add the original key to that list.
  • This handles cases where multiple original keys map to the same value (like 'kuusi' mapping to both 'six' and 'fir') by appending all relevant original keys to the list.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:06:29