Python Forum

Full Version: Fast method of searching a string in a multi-dimension array?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good day. Anyone, please suggest a quicker method to search a string in a multi-dimension array. Given the example below, I want to check if the word 'house' exist in the first column and get the ID beside it. I tried looping and it works, however, as the dictionary adds more words, it takes some time to check if an input string exist and take it's corresponding id. I already have 200K of words in my dictionary, so I need a much faster method.

dictionary = [['dog', 34], ['cat', 2], ['house', 5], ['big', 10], ['bed', 21]]

aim : check if a word exist in the dictionary and retrieve the ID.


Thank you in advance. Your help will be much appreciated. God bless.
Best method for both ease of use and performance: use a real python dictionary

dictionary = {'dog': 34, 'cat':2, 'house': 5, 'big': 10, 'bed': 21}
id=dictionary['cat']
(Feb-20-2017, 11:55 AM)Ofnuts Wrote: [ -> ]Best method for both ease of use and performance: use a real python dictionary
 dictionary = {'dog': 34, 'cat':2, 'house': 5, 'big': 10, 'bed': 21} id=dictionary['cat'] 

Thank you for the response sir. I'll try your suggestions. Thank you very much. God bless you always.
Can fix it so the variable name is right Wink
>>> dictionary = [['dog', 34], ['cat', 2], ['house', 5], ['big', 10], ['bed', 21]]
>>> dictionary = {k[0]: k[1] for k in dictionary}
>>> dictionary
{'dog': 34, 'cat': 2, 'house': 5, 'big': 10, 'bed': 21}
>>> type(dictionary)
<class 'dict'>
Now it's a dictionary,and get() is a good way to check if something is in dict.
>>> dictionary.get('house', 'Not in dict')
5
>>> dictionary.get('hello', 'Not in dict')
'Not in dict'
id is a used Python name Ofnuts.
(Feb-20-2017, 12:16 PM)snippsat Wrote: [ -> ]Can fix it so the variable name is right Wink
>>> dictionary = [['dog', 34], ['cat', 2], ['house', 5], ['big', 10], ['bed', 21]] >>> dictionary = {k[0]: k[1] for k in dictionary} >>> dictionary {'dog': 34, 'cat': 2, 'house': 5, 'big': 10, 'bed': 21} >>> type(dictionary) <class 'dict'>
Now it's a dictionary,and get() is a good way to check if something is in dict.
>>> dictionary.get('house', 'Not in dict') 5 >>> dictionary.get('hello', 'Not in dict') 'Not in dict'
id is a used Python name Ofnuts.

Thank you so much for all of your replies. Great help from this community. God bless you as always.
or just
>>> dict(dictionary)
Output:
{'bed': 21, 'house': 5, 'dog': 34, 'big': 10, 'cat': 2}
(Feb-20-2017, 12:16 PM)snippsat Wrote: [ -> ]id is a used Python name Ofnuts.

Good to know... and useful...