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

Uts*_*iar 13 python dictionary python-3.x

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

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)

zon*_*ndo 13

你可以这么简单地做到这一点:

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


Dav*_*ips 5

我首先使用默认字典交换键/值:

output_dict = defaultdict(list)
for key, values in input_dict.items():
    for value in values:
        output_dict[value.lower()].append(key.lower())
Run Code Online (Sandbox Code Playgroud)

最后排序:

for key, values in output_dict.items():
    output_dict[key] = sorted(values)
Run Code Online (Sandbox Code Playgroud)