因此,我将此索引作为字典。
index = {‘Testfil2.txt’: [‘nisse’, ‘hue’, ‘abe’, ‘pind’], ‘Testfil1.txt’: [‘hue’, ‘abe’,
‘tosse’, ‘svend’]}
我需要反转索引,因此它将是一个字典,其中值的重复项合并为一个键,其中2个原始键作为值,如下所示:
inverse = {‘nisse’ : [‘Testfil2.txt’], ‘hue’ : [‘Testfil2.txt’, ‘Testfil1.txt’],
‘abe’ : [‘Testfil2.txt’, ‘Testfil1.txt’], ‘pind’ : [‘Testfil2.txt’], ‘tosse’ :
[‘Testfil1.txt’], ‘svend’ : [‘Testfil1.txt’]
是的,我手动输入了以上内容。
我的教科书具有反转字典的功能:
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse
它适用于简单的key:value对
但是,当我尝试使用具有诸如值之类的列表的dict的函数时,出现index以下错误消息:
invert_dict(index)
Traceback (most recent call last):
File ““, line 1, in
invert_dict(index)
File ““, line 5, in invert_dict
if val not in inverse:
TypeError: unhashable type: ‘list’
我已经花了一个小时寻找解决方案,这本书没有帮助,我怀疑我可以以某种方式使用元组,但是我不确定如何使用。有什么帮助吗?