Autocomplete function with python dict

In PHP, I had this line. matches = preg_grep('/^for/', array_keys($hash));What she would do is grab the words: fork, form, etc., which are in $ hash.

In Python, I have a dict with 400,000 words. Keys are words that I would like to represent as autocomplete (meaning in this case does not make sense). How can I return the keys from my dictionary matching the input?

For example (as used previously) if I have

my_dic = t{"fork" : True, "form" : True, "fold" : True, "fame" : True}

and I get some input "for", it returns a list "fork", "form".

+5
source share
5 answers
>>> mydict={"fork" : True, "form" : True, "fold" : True, "fame" : True}
>>> [k for k in mydict if k.startswith("for")]
['fork', 'form']

This should be faster than using a regular expression (and enough if you're just looking for the beginning of a word).

+6

, , , ..

, , - , , ?

( ) , .

+3
>>> my_dict = {"fork" : True, "form" : True, "fold" : True, "fame" : True}
>>> import re
>>> [s for s in my_dict if re.search('^for', s) is not None]
['fork', 'form']

, , , : str.startwith, :

>>> [s for s in my_dict if s.startswith('for')]
['fork', 'form']
+1

(, "startswith 3 chars", ), , , .

q = {"fork":1, "form":2, "fold":3, "fame":4}
from collections import defaultdict
q1 = defaultdict(dict)
for k,v in q.items():
    q1[k[:3]][k]=v

.startswith

def getChoices(frag):
    d = q1.get(frag[:3])
    if d is None:
        return []
    return [ k for k in d.keys() if k.startswith(frag) ]

Hopefully this should be much faster than processing just 400,000 keys.

+1
source

You can get the keys to my_dict using my_dict.keys (). You can then search each key to see if it matches your regular expression.

m = re.compile('^for')
keys = []
for key in my_dict.keys():
   if m.match(key) != None:
      keys.append(key)
0
source

All Articles