搜索字典键蟒蛇 [英] Search of Dictionary Keys python

查看:138
本文介绍了搜索字典键蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从python字典对键进行某种索引。这本字典有大约40万个项目,所以我试图避免线性搜索。

I want to know how I could perform some kind of index on keys from a python dictionary. The dictionary holds approx. 400,000 items, so I am trying to avoid a linear search.

基本上,我试图找到 userinput 在任何dict键内。

Basically, I am trying to find if the userinput is inside any of the dict keys.

for keys in dict:
    if userinput in keys:
        DoSomething()
        break

这将是我正在尝试做的一个例子。有没有一种方法可以以更直接的方式搜索,没有循环?或者什么是更有效的方式。

That would be an example of what I am trying to do. Is there a way to search in a more direct way, without a loop ? or what would be a more efficient way.

澄清: userinput 不是关键是什么,例如 userinput 可以是 log ,而密钥是 logfile

Clarification: The userinput is not exactly what the key will be, eg userinput could be log, whereas the key is logfile

编辑:可以在搜索之前完成的任何列表/缓存创建,预处理或组织可以接受的。唯一需要快速的是搜索密钥。

any list/cache creation, pre-processing or organisation that can be done prior to searching is acceptable. The only thing that needs to be quick is the search for the key.

推荐答案

如果您只需要找到从一个前缀,那么您可以使用专辑。存在更复杂的数据结构,用于查找在其中任何地方包含子字符串的键,但它们占用了更多的存储空间,因此它是一种时空间权衡。

If you only need to find keys that start with a prefix then you can use a trie. More complex data structures exist for finding keys that contain a substring anywhere within them, but they take up a lot more space to store so it's a space-time trade-off.

这篇关于搜索字典键蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆