[英]How can I find the key in a dict whose matching value, which is a list, contains X?
I have a python dictionary which maps a number of words to lists of other words. 我有一个python字典,它将多个单词映射到其他单词的列表。 Eg:
例如:
d = {"Hello": ["hi", "hello", "hey", "yo"],
"Goodbye": ["bye", "see ya", "goodbye", "laters"]}
Given a lowercase word, I want to check whether that word is in any of the dictionary values and retrieve the corresponding key. 给定一个小写单词,我想检查该单词是否在任何字典值中,并检索相应的键。
I'm sure there is some elegant solution using some of pythons' functional capabilities ( itertools
perhaps) but its just beyond my reach... 我确定有一些使用
itertools
某些功能的优雅解决方案(也许是itertools
),但这超出了我的能力范围...
Any ideas? 有任何想法吗?
You can have multiple keys matching, so you'd need to produce a set (since order doesn't matter and keys are unique): 您可以有多个匹配的键,因此您需要生成一个集合(因为顺序无关紧要,并且键是唯一的):
{key for key, words in d.iteritems() if search_word in words}
If you are only interested in the first match (because you keep your words unique, say), you can use next()
and a generator expression: 如果您只对第一个匹配感兴趣(例如,因为保持单词唯一),则可以使用
next()
和生成器表达式:
next((key for key, words in d.iteritems() if search_word in words), None)
You probably want to create an inverse index if you need to test for multiple words: 如果您需要测试多个单词,则可能要创建一个反向索引:
reverse_index = {}
for key, words in d.iteritems():
for word in words:
reverse_index.setdefault(word, set()).add(key)
after which you can just use: 之后,您可以使用:
reverse_index.get(search_word, set())
to get the same result. 得到相同的结果。
For unique words in your lists, the reverse index would simply be: 对于列表中的唯一词,反向索引将简单地为:
reverse_index = {word: key for key, words in d.iteritems() for word in words}
reverse_index.get(search_word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.