如何在Python中反转字典(其值为列表)?
发布于 2021-01-29 18:10:57
我想编写一个函数,该函数接收字典作为输入参数,并返回输入字典的反向函数,其中原始字典的值用作返回字典的键,而原始字典的键用作返回值。返回的字典,如下所述:
dict = {'Accurate': ['exact', 'precise'],
'exact': ['precise'],
'astute': ['Smart', 'clever'],
'smart': ['clever', 'bright', 'talented']}
至
dict = {'precise': ['accurate', 'exact'],
'clever': ['astute', 'smart'],
'talented': ['smart'],
'bright': ['smart'],
'exact': ['accurate'],
'smart': ['astute']}
返回字典中的值列表应按升序排序。大小写无关紧要。这意味着所有单词都应转换为小写字母。例如,单词“准确”在原始词典中大写,但在返回的词典中,它用所有小写字母书写。
#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
但是它返回此错误:
Error in evaluating function:
TypeError at line 6
unhashable type: 'list'
关注者
0
被浏览
166
1 个回答