Ves*_*ish 6 python indexing dictionary inverted-index
所以,我把这个索引作为一个词典.
index = {'Testfil2.txt': ['nisse', 'hue', 'abe', 'pind'], 'Testfil1.txt': ['hue', 'abe',
'tosse', 'svend']}
Run Code Online (Sandbox Code Playgroud)
我需要反转索引,因此它将是一个带有重复值的dict,并将两个原始键合并为一个键作为值,如下所示:
inverse = {'nisse' : ['Testfil2.txt'], 'hue' : ['Testfil2.txt', 'Testfil1.txt'],
'abe' : ['Testfil2.txt', 'Testfil1.txt'], 'pind' : ['Testfil2.txt'], 'tosse' :
['Testfil1.txt'], 'svend' : ['Testfil1.txt']
Run Code Online (Sandbox Code Playgroud)
是的,我手动输入上面的内容.
我的教科书有这个函数用于反转词典:
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
Run Code Online (Sandbox Code Playgroud)
它适用于简单的键:值对
但是,当我尝试使用具有列表作为值的dict的函数时,index
我收到此错误消息:
invert_dict(index)
Traceback (most recent call last):
File "<pyshell#153>", line 1, in <module>
invert_dict(index)
File "<pyshell#150>", line 5, in invert_dict
if val not in inverse:
TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)
我已经搜索了一个小时寻找解决方案,这本书没有帮助,我怀疑我可以用某种方式使用元组,但我不确定如何.有帮助吗?
我的反向字典解决方案,如何创建新字典new_dic
:
new_dic = {}
for k,v in index.items():
for x in v:
new_dic.setdefault(x,[]).append(k)
Run Code Online (Sandbox Code Playgroud)
输出:
{'tosse': ['Testfil1.txt'], 'nisse': ['Testfil2.txt'], 'svend': ['Testfil1.txt'], 'abe': ['Testfil1.txt', 'Testfil2.txt'], 'pind': ['Testfil2.txt'], 'hue': ['Testfil1.txt', 'Testfil2.txt']}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了,您想使用val not in inverse
它,但是如果“列表在字典中”,则无法检查它。(val
是列表)
对于您的代码,简单的更改就可以满足您的要求:
def invert_dict(d):
inverse = dict()
for key in d:
# Go through the list that is saved in the dict:
for item in d[key]:
# Check if in the inverted dict the key exists
if item not in inverse:
# If not create a new list
inverse[item] = [key]
else:
inverse[item].append(key)
return inverse
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4887 次 |
最近记录: |