如何在Python中反转字典(其值为列表)? [英] How to reverse a dictionary (whose values are lists) in Python?

查看:257
本文介绍了如何在Python中反转字典(其值为列表)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to write a function that receives a dictionary as input argument and returns a reverse of the input dictionary where the values of the original dictionary are used as keys for the returned dictionary and the keys of the original dictionary are used as value for the returned dictionary as explained below:

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']}

返回字典中的值列表应按升序排序.大小写无关紧要.这意味着所有单词都应转换为小写字母.例如,原始"一词在原始字典中大写,而在返回的字典中则用所有小写字母书写.

The list of values in the returned dictionary should be sorted in ascending order. Capitalization does not matter. This means that all the words should be converted to lower case letters. For example the word "Accurate" is capitalized in the original dictionary but in the returned dictionary it is written with all lower case letters.

#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'

推荐答案

您可以像这样非常简单地完成此操作:

You can do it very simply like this:

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

这篇关于如何在Python中反转字典(其值为列表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆