我想编写一个函数,它接收一个字典作为输入参数,并返回该输入字典的反转版本,其中原始字典的值用作返回字典的键,原始字典的键用作返回字典的值,如下所述:
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']}
返回结果为:返回的字典值列表应按升序排序。大小写不敏感。这意味着所有单词都应转换为小写字母。例如,单词“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
但是它返回了这个错误信息:
Error in evaluating function:
TypeError at line 6
unhashable type: 'list'
'Accurate': ['exact', 'precise']
会变成'precise': ['accurate', 'exact']
而不是'exact': ['accurate', 'precise']
?就您的错误信息而言,列表不能作为字典键,但我认为更大的问题是需要澄清您的任务。 - Daniel Standage{'a': ['b', 'c']}
变成了{'b': ['a'], 'c': ['a']}
。@DanielStandage,@SteinarLima - Vincent Savard