简体   繁体   English

如何在字典的匹配值(包含列表)包含X的字典中找到键?

[英]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.

相关问题 如何在嵌套字典中返回键/值对,其值是包含所述字典的列表 - How to return key/value pairs in nested dict whose value is a list that contains said dict 我如何追加到列表中,该列表是dict中的键值? - how can I append to a list which is value of a key in dict? 通过匹配字典值来找到列表中字典的已定义键的值 - Find the value of the defined key of a dict within a list, by matching the dict values 如果没有if语句,如何找到dict中存在哪个键? - How can I find which key exists in dict without if statements? 如何编码像字典列表这样的对象,其中包含Unicode密钥或utf8值? - How to encode object like list of dict which contains unicode key or value to utf8? 如何通过键入列表查找字典值 - How to find dict value by Key in list 如何在Dict {key:List}中找到最小值? - How to find the minimum value in a Dict{key:List}? 如何从列表中提取值包含项的对应键? - How to extract the corresponding key whose value contains the item from a list? 如何将 dict keyx:valuex 列表转换为 dict key:keyx, value:valuex 列表? - How can I convert a list of dict keyx:valuex to a list dict key:keyx, value:valuex? 如何基于Python中的匹配键将键值对添加到另一个字典列表中的现有字典列表中 - How to append key value pair to an existing list of dict from another list of dict based on matching Key in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM