简体   繁体   中英

Find index in a list of dictionaries

If I know the key name, how can I find the list index when data is structured like this?

foo = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]

For example, given the string 'key2' , what is its index in the list above?

My current code:

for i in xrange(len(foo)):
    if foo[i].keys()[0] == 'key1':
        print i

I'm curious however if there is some slick technique that does not require an explicit loop.

You can use next , enumerate , and a generator expression :

>>> foo = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
>>> next((i for i,d in enumerate(foo) if 'key1' in d), None)
0
>>> next((i for i,d in enumerate(foo) if 'key2' in d), None)
1
>>> next((i for i,d in enumerate(foo) if 'key3' in d), None)
2
>>> next((i for i,d in enumerate(foo) if 'key4' in d), None)
>>>

Note that you can also replace None with any default value:

>>> next((i for i,d in enumerate(foo) if 'key4' in d), 'not found')
'not found'
>>>

Also, I would like to mention that doing:

if foo[i].keys()[0] == 'key1':

will not always work if the dictionaries have more than one item. This is because a dictionary's keys are naturally unordered:

>>> d = {'abc':1, 'xyz':2}
>>> d.keys()
['xyz', 'abc']
>>>

In addition, there is no need to call the keys method of a dictionary to search its keys because you have the in operator :

>>> 'abc' in d
True
>>> 'def' in d
False
>>>

This solution is also a lot more efficient because it avoids creating an unnecessary list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM