小编Ves*_*ish的帖子

使用列表值反转字典

所以,我把这个索引作为一个词典.

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 …
Run Code Online (Sandbox Code Playgroud)

python indexing dictionary inverted-index

6
推荐指数
2
解决办法
4887
查看次数

标签 统计

dictionary ×1

indexing ×1

inverted-index ×1

python ×1