Reputation: 16469
How could I find the index of 'node4'
in my dataset a? I want node4
to be my input for this particular function.
ex:
a = [
{'node1':['node2','node3','node5']},
{'node2':['node1','node8','node10']},
{'node3':['node4','node2']},
{'node4':['node2','node1','node3']},
{'node5':['DEADEND']},
{'node6':['GOAL']}
....
]
Upvotes: 2
Views: 1854
Reputation: 2393
Or just like that:
[index for index, record in enumerate(a) if 'node4' in record.keys()][0]
Upvotes: 1
Reputation: 693
I would build a dictionary with the indices:
>>> index = {key: i for i, elem in enumerate(a) for key in elem}
>>> index['node4']
3
This requires going over the entire list once to build the dictionary (which is the worst case for one-time use anyway) but is then faster if you need it more than once.
Upvotes: 1
Reputation: 239453
def findIndex(inKey):
for idx, item in enumerate(a):
if inKey in item:
return idx
return None
Upvotes: 2
Reputation: 250911
>>> next((i for i,x in enumerate(a) if 'node4' in x), None)
3
Upvotes: 5