gpt4 book ai didi

python - 用列表值反转字典

转载 作者:太空狗 更新时间:2023-10-29 22:09:03 25 4
gpt4 key购买 nike

所以,我将这个索引作为字典。

index = {'Testfil2.txt': ['nisse', 'hue', 'abe', 'pind'], 'Testfil1.txt': ['hue', 'abe', 
'tosse', 'svend']}

我需要反转索引,这样它将成为一个字典,其中重复的值合并到一个键中,两个原始键作为值,如下所示:

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

它适用于简单的键值对

但是,当我尝试使用具有列表作为值(例如我的 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'

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

最佳答案

我的字典反转解决方案。但是,它会创建一个新字典 new_dic:

new_dic = {}
for k,v in index.items():
for x in v:
new_dic.setdefault(x,[]).append(k)

输出:

{'tosse': ['Testfil1.txt'], 'nisse': ['Testfil2.txt'], 'svend': ['Testfil1.txt'], 'abe': ['Testfil1.txt', 'Testfil2.txt'], 'pind': ['Testfil2.txt'], 'hue': ['Testfil1.txt', 'Testfil2.txt']}

关于python - 用列表值反转字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com