Reputation: 10269
I have a list(stop_list) of dictionary. the structure of dictionary is
stop_id : ""
stop_name : ""
Now, I have a name string which is to be matched against stop_name
, and get the stop_id
corresponding to that.
Is there any efficient way of doing it? I could come up with only for loop.
for entry in stop_list:
if name = entry['name']:
id = entry['id']
break
Upvotes: 0
Views: 111
Reputation: 379
After looking at the code it seems that you get the dictionary having the same name. If your name are unique you should consider using a dict for your dicts where the key would be the name.
1 - this will allow you not to browse the list (it is costly compared to dict lookup)
2 - this is more readable
3 - you call entry['name'] only once
Let's say that your stopdict would look like that
stopdict= {
'stop1' : {'name' : 'stop1', 'id' : 1}
'stop2' : {'name' : 'stop2', 'id' : 2}
}
accessing the id would look like that :
stopdict[entry['name']]['id']
Upvotes: 0
Reputation: 239653
You can use generator expression and next
function, like this
next(entry['id'] for entry in stop_list if entry['name'] == name)
This will iterate through the stop_list
and when it finds a match, it will yield entry['id']
. This will be better because this doesn't have to iterate the entire list.
Another advantage is, if there are more than one matches, then you can use the same expression to get the next id also, like this
>>> ids = next(entry['id'] for entry in stop_list if entry['name'] == name)
>>> next(ids)
# you will get the first matching id here
>>> next(ids)
# you will get the second matching id here
If there is going to be more than one lookups, and given the names are unique, then preprocess the list and create a dictionary, like this
lookup = {entry['name']: entry['id'] for entry in stop_list}
then you can do lookups in constant time, with lookup[name]
. This would be the most efficient way if the names are unique and if there are more than one lookups
Upvotes: 4