如何在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 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以像这样非常简单地进行操作:

    newdict = {}
    for key, value in olddict.items():
        for string in value:
            newdict.setdefault(string, []).append(key)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看