Liondancer
Liondancer

Reputation: 16469

Finding index of a dictionary in a list by key value

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

Answers (4)

Andrei Boyanov
Andrei Boyanov

Reputation: 2393

Or just like that:

    [index for index, record in enumerate(a) if 'node4' in record.keys()][0]

Upvotes: 1

Daniel
Daniel

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

thefourtheye
thefourtheye

Reputation: 239453

def findIndex(inKey):
    for idx, item in enumerate(a):
        if inKey in item:
            return idx
    return None

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

Use next and enumerate:

>>> next((i for i,x in enumerate(a) if 'node4' in x), None)
3

Upvotes: 5

Related Questions