小编Uts*_*iar的帖子

如何在Python中反转字典(其值为列表)?

我想编写一个接收字典作为输入参数的函数,并返回输入字典的反转,其中原始字典的值用作返回字典的键,原始字典的键用作值的值.返回字典,如下所述:

dict = {'Accurate': ['exact', 'precise'], 
        'exact': ['precise'], 
        'astute': ['Smart', 'clever'], 
        'smart': ['clever', 'bright', 'talented']}
Run Code Online (Sandbox Code Playgroud)

dict = {'precise': ['accurate', 'exact'], 
        'clever': ['astute', 'smart'], 
        'talented': ['smart'], 
        'bright': ['smart'],
        'exact': ['accurate'],
        'smart': ['astute']}
Run Code Online (Sandbox Code Playgroud)

返回字典中的值列表应按升序排序.资本化并不重要.这意味着所有单词都应转换为小写字母.例如,单词"Accurate"在原始字典中大写,但在返回的字典中,它用所有小写字母书写.

#My code is:
from collections import defaultdict
def reverse_dictionary(input_dict):
   d = defaultdict(list)
   for v,k in input_dict.items():
       d[k].append(v)
       return d
Run Code Online (Sandbox Code Playgroud)

但它返回此错误:

Error in evaluating function:
TypeError at line 6
unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)

python dictionary python-3.x

13
推荐指数
2
解决办法
1万
查看次数

标签 统计

dictionary ×1

python ×1

python-3.x ×1