使用列表值反转字典

编程入门 行业动态 更新时间:2024-10-08 13:31:03
本文介绍了使用列表值反转字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以,我将此索引作为字典.

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

它适用于简单的键值对

但是,当我使用具有列表作为值(例如我的 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 inverse 但是如果list is在字典中".(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

更多推荐

使用列表值反转字典

本文发布于:2023-07-19 13:41:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!