如何在Python中扭转字典? [英] How to reverse a dictionary in Python?

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

问题描述

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

  dict = {'Accurate':['exact','precise'], 
'exact':['exact'],
'astute':['Smart','clever'],
'smart':['clever','bright'有才华的']}

  dict = {'exact':['准确','exact'],
'clever':['astute','smart'],
'talented' :['smart'],
'bright':['smart'],
'exact':['准确'],
'smart':['astute']}

返回的字符串中的值列表离子应按升序排列。资本化并不重要。这意味着所有的单词都应该转换成小写字母。例如,Accurate一词在原始字典中大写,但在返回的字典中,它用全部小写字母写。

 #我的代码是:
从集合import defaultdict
def reverse_dictionary(input_dict):
d = defaultdict(list)
for v,k in input_dict.items():
d [k] .append(v)
return d

但它返回此错误虽然:

 评估函数中的错误:
第6行中的TypeError
unhashable类型:'list'


解决方案

你可以这样做:

  newdict = {} 
为key,value在olddict.items()中:
为字符串值:
newdict.setdefault(string,[])。append(key)


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)

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

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