Find the index of a dict within a list, by matching the dict’s value

I have a list of dicts:

list = [{'id':'1234','name':'Jason'},

How can I efficiently find the index position [0],[1], or [2] by matching on name = ‘Tom’?

If this were a one-dimensional list I could do list.index() but I’m not sure how to proceed by searching the values of the dicts within the list.


lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]

tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
# 1

If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

def build_dict(seq, key):
    return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}