0

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
1
  • Why not create a mapping {stop_name: stop_id, ...} (if the names are unique) or {stop_name: [stop_id, ...], ...} (if not)? You build it once then lookups by name are O(1). Commented Jun 5, 2015 at 7:18

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

I am sure that, there won't be second matching item. So, this will work right? Or another better way considering there won't be second item..
@IshanBhatt Will you be doing the lookups more than once?
Nope, only one lookup.
@IshanBhatt Then what you have in the question itself should be enough.
0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.