Python字典模糊键搜索

Python字典模糊键搜索,python,dictionary,search,Python,Dictionary,Search,我想知道是否有办法在python字典中进行“模糊”键搜索。例如,我有一本这样的字典: data = { "Google.com" : value1, "StackOverFlow": value2, ....} 如果我有一根绳子 name= "Google" or name = "google" or even name = "gooogle" 我想访问字典中的value1(其键为“Google.com”),我该怎么做?我知道我可以遍历keys列表并进行一些字符串处理,但是如果我有多个名字,

我想知道是否有办法在python字典中进行“模糊”键搜索。例如,我有一本这样的字典:

data = { "Google.com" : value1, "StackOverFlow": value2, ....}
如果我有一根绳子

name= "Google" or name = "google" or even name = "gooogle"
我想访问字典中的value1(其键为“Google.com”),我该怎么做?我知道我可以遍历keys列表并进行一些字符串处理,但是如果我有多个名字,我想进行这种模糊的搜索,它将是O(n^2),对吗?有什么有效的方法可以做到这一点吗?假设数据字典非常大


希望我的问题很清楚…

在搜索时没有有效的模糊键。Python的dict使用散列来查找字典中的位置,对于类似的字符串,散列是非常不同的。让我们看看:

assert hash("Google.com") == 4399753695393964520
assert hash("Google.co") == -9213236188503134626
至少在我的操作系统中

结论:使用类似的键很少能“接近”所需的值


所以:不。你不能避免使用dicts的O(n^2)。

如果你想做一些模糊搜索,那么你必须有效地提出你自己的哈希算法。或者创建自己的字典变体,只需覆盖
\uuuu getitem\uuuu
和相关方法

以下是一个例子:

from jellyfish import soundex

data = {soundex('google'): 'google.com', soundex('stackoverflow'): 'stackoverflow.com'}
print(data[soundex('gooooogle')])
# Should print `google.com`, because soundex pretty much ignores vowels
或者另一种选择:

from jellyfish import soundex

class SoundexDict(dict):
    # __init__ and __repr__ is left as an exercise for the reader
    def __getitem__(self, key):
        return super().__getitem__(soundex(key))

    def __setitem__(self, key, value):
        super().__setitem__(soundex(key), value)

mydict = SoundexDict()
mydict['google'] = 'google.com'
print(mydict['gewgle'])  # prints 'google.com'

1.你在寻找“模糊搜索”。2.是的,这将是非常低效的,如果你不能依赖精确的键哈希匹配,你就无法充分利用字典。如果你有
google.com
google.com
什么应该
oogle.com
匹配?有一个类似的问题:它指向一个实现:用这样的语法填充数据字典似乎是非法的:data[soundex](名称)]我的意思是,我得到了TypeError:预期为unicode,得到stry您可能正在使用Python2。您可能需要使用
mydict[u'google']='google.com'
,或者调整设置器以执行
soundex(key.encode())
或其他操作。