Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get index of dictionary item in list [duplicate]

I have a list li:

[
{name: "Tom", age: 10},
{name: "Mark", age: 5},
{name: "Pam", age: 7}
]

I want to get the index of the item that has a certain name. For example, if I ask for "Tom" it should give me: 0. "Pam" should give me 2.

like image 706
dkgirl Avatar asked Jan 01 '11 11:01

dkgirl


People also ask

How do I find the index of a duplicate element in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.

Can index have duplicates?

Duplicate indexes are those that exactly match the Key and Included columns. That's easy. Possible duplicate indexes are those that very closely match Key/Included columns.


2 Answers

>>> from operator import itemgetter
>>> map(itemgetter('name'), li).index('Tom')
0
>>> map(itemgetter('name'), li).index('Pam')
2

If you need to look up a lot of these from the same list, creating a dict as done in Satoru.Logic's answer, is going to be a lot more efficent

like image 61
John La Rooy Avatar answered Oct 15 '22 02:10

John La Rooy


You may index the dicts by name

people = [ {'name': "Tom", 'age': 10}, {'name': "Mark", 'age': 5} ]
name_indexer = dict((p['name'], i) for i, p in enumerate(people))
name_indexer.get('Tom', -1)
like image 43
satoru Avatar answered Oct 15 '22 00:10

satoru