10

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.

Bastien Léonard
  • 60,478
  • 20
  • 78
  • 95
dkgirl
  • 4,489
  • 7
  • 24
  • 26

2 Answers2

27
>>> 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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 2
    +1, I didn't know this. I had assumed that this problem is too trivial to have a library function like `itemgetter` and always looped over the dict items :D – 0xc0de Jan 21 '12 at 14:27
  • in python3 it seems the map needs to be wrapped in a list to provide the index method – Vincent De Smet May 28 '17 at 14:01
17

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)
satoru
  • 31,822
  • 31
  • 91
  • 141