【问题标题】:Return the key if the each word in a list of words exists in a dictionary having a list of words as value如果单词列表中的每个单词都存在于以单词列表为值的字典中,则返回键
【发布时间】:2021-07-23 08:59:32
【问题描述】:

我有一个独特的用例。我的主要要求是效率和速度。我有一个长度为 40,000 的单词列表和一个格式为 data: {id1: ['hi','how'],id2:['I','love]..} 且长度为 250,000 的字典。我在这里遇到了很多关于 SO 的问题,但找不到一个可能有效的问题。

如何检查单词列表中的每个单词是否存在于每个字典的单词列表(值)中?通常,可以执行以下操作:

all_words = get_vocabulary(data)
index = {}
for word in all_words:
    for doc, tokens in data.items():
        if word in tokens :
            ''' do something with key and tokens'''

通过这样做,我可以检查单词是否存在并完成其余的工作。但是,我的字典和列表都很大,这需要很长时间。

如果我必须一遍又一遍地翻字典,它显然标志着@DeepSpace in this question提到的问题

非常感谢您提供的任何帮助。

【问题讨论】:

  • 澄清一下,每次发现你要do something吗?还是应该只做一次?
  • 所以基本上,我会创建一个反向索引。如果找到,我将存储找到该单词的 ID,如下所示:{'love':[id1,id2, id3..],'hate':[id9,id1,id4].}
  • 哦,这和我以为你问的不一样……

标签: python list dictionary for-loop list-comprehension


【解决方案1】:

您可以从字典中创建索引以加快搜索速度。例如:

all_words = ["word1", "word2"]

dct = {
    "id1": ["tis", "word1", "and", "word2"],
    "id2": ["word3", "word4"],
    "id3": ["word2", "only"],
}

# create index dictionary:
index_dct = {}
for k, v in dct.items():
    for word in v:
        index_dct.setdefault(word, []).append(k)

# index dictionary is:
# {
#     "tis": ["id1"],
#     "word1": ["id1"],
#     "and": ["id1"],
#     "word2": ["id1", "id3"],
#     "word3": ["id2"],
#     "word4": ["id2"],
#     "only": ["id3"],
# }


# now the search:
for word in all_words:
    if word in index_dct:
        for doc in index_dct[word]:
            print("Word: {} Doc: {} Tokens: {}".format(word, doc, dct[doc]))

打印:

Word: word1 Doc: id1 Tokens: ['tis', 'word1', 'and', 'word2']
Word: word2 Doc: id1 Tokens: ['tis', 'word1', 'and', 'word2']
Word: word2 Doc: id3 Tokens: ['word2', 'only']

【讨论】:

  • 即使这不能解决 OP 的问题,很高兴我阅读了您的解决方案。在我的职业生涯中使用 python 已经有一段时间了,但从来不知道字典上的 setdefault
  • 恰恰相反,这正好解决了我的问题,而且速度超级快!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2020-05-13
  • 2015-05-31
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2021-08-14
相关资源
最近更新 更多