Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autocomplete-like feature with a python dict

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

In Python, I have a dict with 400,000 words. It's keys are words I'd like to present in an auto-complete like feature (the values in this case are meaningless). How would I be able to return the keys from my dictionary that match the input?

For example (as used earlier), if I have

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

and I get some input "for", It'll return a list of "fork", "form".

like image 630
tipu Avatar asked Jun 03 '10 16:06

tipu


1 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 sufficient if you're just looking for word beginnings).

like image 131
Tim Pietzcker Avatar answered Oct 15 '22 17:10

Tim Pietzcker