python字典的值保存为列表,如何在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']}

to

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

But it returns this error though:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值