用列表值反转字典 [英] Inverting a dictionary with list values
问题描述
所以,我将此索引作为字典.
So, I have this index as a dict.
index = {'Testfil2.txt': ['nisse', 'hue', 'abe', 'pind'], 'Testfil1.txt': ['hue', 'abe',
'tosse', 'svend']}
我需要反转索引,这样它才能成为字典,将重复的值合并为一个键,并以2个原始键作为值,如下所示:
I need to invert the index so it will be a dict with duplicates of values merged into one key with the 2 original keys as values, like this:
inverse = {'nisse' : ['Testfil2.txt'], 'hue' : ['Testfil2.txt', 'Testfil1.txt'],
'abe' : ['Testfil2.txt', 'Testfil1.txt'], 'pind' : ['Testfil2.txt'], 'tosse' :
['Testfil1.txt'], 'svend' : ['Testfil1.txt']
是的,我手动输入了以上内容.
Yes, I typed the above by hand.
我的教科书具有反转字典的功能:
My textbook has this function for inverting dictionaries:
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
它对于简单的键:值对工作正常
It works fine for simple key:value pairs
但是,当我尝试使用包含诸如index
之类的值的列表的dict时,我得到以下错误消息:
BUT, when I try that function with a dict that has lists as values such as my index
I get this error message:
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'
我已经花了一个小时寻找解决方案,这本书没有帮助,我怀疑我可以以某种方式使用元组,但是我不确定如何使用.有帮助吗?
I have searched for an hour looking for a solution, the book is no help, and I suspect that I can use tuples in some way, but I am not sure how. Any help?
推荐答案
我已经尝试过,并且您想使用val not in inverse
,但是无法检查列表是否在字典中". (val
是列表)
I've tried around and you want to use val not in inverse
but it can't be checked if a "list is in a dict". (val
is a list)
对您的代码进行简单的更改即可完成您想要的操作:
For your code a simple change will do what you want:
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
这篇关于用列表值反转字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!