检查词典中的单词列表
你好,我有一个单词列表,我想检查字典与键和值。其实我只想知道列表中的某些单词是否出现在字典的值中。这在python中可能是一件容易的事情,但我是一名初学者,而且我只是不断收到显然不明白的错误。检查词典中的单词列表
这里是我的代码(字典就在眼前):
words = ["give", "a", "pearl", "to", "the" "elephant"]
for k, v in dic.items():
for word in words:
if word in v:
print(v)
或者:
relevant = {d:reldic[d] for d in reldic if words in reldic[d]}
print(relevant)
错误,我得到:
TypeError: unhashable type: 'list'
缺少什么?
提前致谢!
更新:
好吧,这有助于更好地理解问题。那我的数据看起来像:
2000/9/1 abe D mes Español inan.|m.|m.
2000/9/1 abe D luna Español inan.|m.|m.
2000/9/1 abe D sol Español inan.|m.|m.
2000/9/2 gacuri D meter Español v.t.
2000/9/2 acuri D meter Español v.t.
2000/9/2 yacuri D meter Español v.t.
然后,我有相关的块的集合:
dic = collections.defaultdict(set)
for e in entries:
dic[e[1]].add(e[3])
,最后我的字典里:
reldic = {d:dic[d] for d in dic if len(dic[d]) > 1}
这个特定的错误是告诉你,你不能使用一个列表(或其他不是'可哈希'的)作为字典的关键字。举个例子:
# all of the following are ok
d = dict()
d[3] = True
d['text'] = True
d[(3, 'text')] = True
a_list = []
d[a_list] = 'ok?' # this is not ok
你的代码的第一个版本很好,所以你可以使用它。看起来你试图用字典理解来实现它,但是你拥有的东西有点不合理。
最近,tersest代码,你写的东西可能是这样的:
relevant = {k:v for k,v in dic.items() if any(filter(lambda w: w in v, words))}
但它肯定是读一个奇怪的是非显而易见的事情。说实话,我会先写你的第一个代码示例,再阅读一些关于字典理解的东西,以更好地了解它们应该用在哪里。
编辑:现在我们有数据本身,我们可以解决这个好一点。让我们开始使用你的格式为:
dic = {'abe': {'luna', 'mes', 'sol'},
'acuri': {'meter'},
'gacuri': {'meter'},
'yacuri': {'meter'}}
我们可以使用组操作,使这个更有效(具体取决于数据等各种尺寸,你必须进行测试)。
words = ["give", "a", "pearl", "to", "the", "meter"]
ws = set(words)
[k for k,v in dic.items() if v.intersection(ws)]
# ['acuri', 'gacuri', 'yacuri']
不过说真的,这一切都有点倒退,你在你的整个索引,这部分失败摆在首位的指数点必须循环。它在我看来你想创建你的索引在相反的方向开始。
dic = collections.defaultdict(set)
for e in entries:
dic[e[3]].add(e[1])
# note, we're now mapping from word -> book(?)
dic = {'mes': {'abe'},
'sol': {'abe'},
'meter': {'acuri', 'gacuri', 'yacuri'},
'luna': {'abe'}}
# now it's simple and efficient to find all the books that contain the words
sets_of_books_containing_words = [dic[w] for w in words if w in dic]
# and to combine that together into a single set
books_containing_one_of_the_words = set.union(*sets_of_books_containing_words)
Thanks @Aidan Kane,据我所知,列表不能是字典中的关键字,但是我有一个我想检查字典的单词列表,我不想将列表用作关键字。我希望我能理解你的权利! – 2014-10-11 13:31:16
是的,我明白了。我的代码的第一部分仍然产生错误:'TypeError:unhashable type:'list''。我刚刚检查过,'v'的类型是'set()',这可能是问题吗? – 2014-10-11 13:37:23
关于阅读更多的部分,这里是一个问题,是不直接相关的,但在答案和链接中有一些很好的阅读材料:http://stackoverflow.com/questions/9010222/how-can-python-dict-have-多密钥与同一哈希。我也会投票给你。 – Elric 2014-10-11 13:40:06
什么是'reldic'? – thefourtheye 2014-10-11 13:20:36
你可能试图用一个列表作为字典键,这是不允许的 – wim 2014-10-11 13:21:08
对不起,不是“reldic”只是“字典”,更新 – 2014-10-11 13:22:05