你好,我有一个单词列表,我想检查具有键和值的字典。实际上我只是想知道列表中的某些单词是否出现在字典的值中。这在python中可能是一个简单的任务,但我是初学者,我只是一直得到同样的错误,我显然不明白。
这是我的代码(dict就在眼前):
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}
答案 0 :(得分: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
您的代码的第一个版本很好,所以您可以使用它。看起来你正试图用字典理解来做,但你所拥有的是一点非感性。
你所写的最接近,最简洁的代码可能是:
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'}}
我们可以使用set操作来提高效率(取决于各种大小的数据等,你必须测试)。
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)
答案 1 :(得分:-2)
d是列表。列表不能成为字典中的密钥。