查找键以相同前缀开头的字典值的更有效方法

More efficient way to look up dictionary values whose keys start with same prefix

我有一本字典,其键位于共享相同前缀的集合中,如下所示:

d = { "key1":"valA", "key123":"valB", "key1XY":"valC",
      "key2":"valD", "key2-22":"valE" }

给定一个查询字符串,我需要查找与以该前缀开头的键关联的所有值,例如对于 query="key1" 我需要得到 ["valA", "valB", "valC"]

我下面的实现有效,但对于大量查询来说太慢了,因为字典 d 有大约 30,000 个键,而且大多数键的长度都超过 20 个字符:

result = [d[s] for s in d.keys() if s.startswith(query)]

有没有faster/more有效的方法来实现这个?

您可以避免生成由 dict.keys() 生成的中间列表(在 python 2.x 中):

result = [d[key] for key in d if key.startswith(query)]

但是您很可能希望使用 trie 而不是字典,因此您可以找到与具有公共前缀的键关联的所有值(trie 类似于基于前缀的树) .

Here 你可以找到一些不同的尝试实现。

A trie for keys "A", "to", "tea", "ted", "ten", "i", "in", and "inn". (source wikipedia)


让我们比较一下不同解决方案的时间安排:

# create a dictionary with 30k entries
d = {str(x):str(x) for x in xrange(1, 30001)}
query = '108'

# dict with keys()
%timeit [d[s] for s in d.keys() if s.startswith(query)]

    100 loops, best of 3: 8.87 ms per loop

# dict without keys()
%timeit [d[s] for s in d if s.startswith(query)]

    100 loops, best of 3: 7.83 ms per loop

# 11.72% improvement

# PyTrie (https://pypi.python.org/pypi/PyTrie/0.2)
import pytrie
pt = pytrie.Trie(d)

%timeit [pt[s] for s in pt.iterkeys(query)]

    1000 loops, best of 3: 320 µs per loop

# 96.36% improvement

# datrie (https://pypi.python.org/pypi/datrie/0.7)
import datrie
dt = datrie.Trie('0123456789')
for key, val in d.iteritems():
    dt[unicode(key)] = val

%timeit [dt[s] for s in dt.keys(unicode(query))]

    10000 loops, best of 3: 162 µs per loop

# 98.17% improvement

sortedContainers 库有一个 SortedDict implementation, once you have sorted dict you can bisect_left to find where to start, bisect_right to find the last position then use irange 来获取范围内的键:

from sortedcontainers import SortedDict
from operator import itemgetter
from itertools import takewhile


d = { "key1":"valA", "key123":"valB", "key1XY":"valC",
  "key2":"valD", "key2-22":"valE","key3":"foo" }

key = "key2"
d = SortedDict(sorted(d.items(), key=itemgetter(0)))
start = d.bisect_left(key)
print([d[key] for key in takewhile(lambda x: x.startswith("key2"), d.irange(d.iloc[start]]))
['valD', 'valE']

一旦使用 sorteddict 维护一个 sorteddict 就会更加有效:

In [68]: l = ["key{}".format(randint(1,1000000)) for _ in range(100000)] 
In [69]: l.sort()    
In [70]: d = SortedDict(zip(l,range(100000)))

In [71]: timeit [d[s] for s in d.keys() if s.startswith("key2")]
10 loops, best of 3: 124 ms per loop

In [72]: timeit [d[s] for s in d if s.startswith("key2")]
10 loops, best of 3: 24.6 ms per loop

In [73]: %%timeit
key = "key2"
start = d.bisect_left(key)
l2 =[d[k] for k in takewhile(lambda x: x.startswith("key2"),d.irange(d.iloc[start]))]
   ....: 

100 loops, best of 3: 5.57 ms per loop

您可以使用 suffix tree:

#!/usr/bin/env python2
from SuffixTree import SubstringDict # $ pip install https://github.com/JDonner/SuffixTree/archive/master.zip

d = { "key1":"valA", "key123":"valB", "key1XY":"valC",
      "key2":"valD", "key2-22":"valE" }

a = '\n' # anchor
prefixes = SubstringDict()
for key, value in d.items(): # populated the tree *once*
    prefixes[a + key] = value # assume there is no '\n' in key

for query in ["key1", "key2"]: # perform queries
    print query, prefixes[a + query]

输出

key1 ['valC', 'valA', 'valB']
key2 ['valE', 'valD']