用列表值反转字典


狗头军师
2025-03-13 06:47:09 (26天前)

因此,我将此索引作为字典。

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’]
是的,我手动输入了以上内容。

我的教科书具有反转字典的功能:


  1. 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以下错误消息:


  1. 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

我已经花了一个小时寻找解决方案,这本书没有帮助,我怀疑我可以以某种方式使用元组,但是我不确定如何使用。有什么帮助吗?

2 条回复
  1. 1# v-star*위위 | 2020-08-21 14-29

    我已经尝试过了,您想使用val not in inverse它,但是如果“列表在字典中”就无法检查它。(val是列表)

    对于您的代码,简单的更改就可以满足您的要求:

    1. def invert_dict(d):
    2. inverse = dict()
    3. for key in d:
    4. # Go through the list that is saved in the dict:
    5. for item in d[key]:
    6. # Check if in the inverted dict the key exists
    7. if item not in inverse:
    8. # If not create a new list
    9. inverse[item] = [key]
    10. else:
    11. inverse[item].append(key)
    12. return inverse
登录 后才能参与评论