How to find index of a dictionary key value within a list? (python)

Question:

Lets say I have a list such as:

listofpeople = [{'Jack': ['Blue', 'Red', 'Green']}, {'Barry': ['Red', 'Green', 'Orange']}]

If I were to go about searching for the index of ‘Jack’, how would I find his index if ‘Jack’ is a key value of a dictionary within a list?

Asked By: BoopityBoppity

||

Answers:

Try this:

jack_indices = [i for i in range(len(listofpeople)) if listofpeople[i].keys() == ['Jack']]

Alternatively, if your dictionaries can have multiple keys and you’re looking for all indices of those which contain ‘Jack’ as a key you could do:

jack_indices = [i for i in range(len(listofpeople)) if 'Jack' in listofpeople[i].keys()]
Answered By: Andrew Brown

Maybe something like this:

listofpeople = [{'Jack': ['Blue', 'Red', 'Green']}, {'Barry': ['Red', 'Green', 'Orange']}]
idx = 0
for i in listofpeople:
  for j in i.keys():
    if j == 'Jack':
      print(idx)
      break
  idx += 1
Answered By: DanteVoronoi
name = "Jack"
for index, value in enumerate(listofpeople):
    if name in value.keys():
        print('{} at index {}'.format(value, index))
>>>{'Jack': ['Blue', 'Red', 'Green']} at index 0
Answered By: Veera Balla Deva
>>> listofpeople = [{'Jack': ['Blue', 'Red', 'Green']}, {'Barry': ['Red', 'Green', 'Orange']}]
>>> [i for i, d in enumerate(listofpeople) if "Jack" in d.keys()]
[0]
Answered By: Sean Breckenridge
>>> l = [{'Jack': ['Blue', 'Red', 'Green']}, {'Barry': ['Red', 'Green', 'Orange']}]
>>> import itertools as it
>>> list(filter(lambda x: x[1] == 'Jack', enumerate(it.chain(*l))))
[(0, 'Jack')]

I am unpacking the variable l into positional arguments, which I then pass to itertools.chain(). This results in a flat list with the values ['Jack', 'Barry']. The built-in function enumerate() returns a tuple containing a count (starts from 0) and the values obtained from iterating over iterable. The next and last thing I do is filtering with small anonymous function all the tuples where the second element (x[1]) equals to the desired str.

Answered By: Yannic Hamann

Keeping it simple –

for people in listofpeople:
    if 'Jack' in people:
        idx = listofpeople.index(people)
        break

If idx has a value at the end you have the index of the element that had ‘jack’ as a key

Answered By: Karan Shishoo

Whatever you do, please don’t look up the presence of a dictionary key from the list returned by d.keys(). Much more efficient is to query the dictionary directly. (Disclaimer: apparantly this only applies to Python 2, as the view returned in Python 3 also enables efficient membership tests…)

Then you can just fetch the index of the first item that has the key, e.g., like this:

idx = next((i for i,d in enumerate(listofpeople) if "Jack" in d), None)

For reference:

Answered By: moooeeeep

This is definitely not the best way, but it is different from everyone else’s answers:

name = 'Jack'
idx = None
for ii, people in enumerate(listofpeople):
  try:
    people['Jack']
    idx = ii
    break
  except KeyError:
    continue
Answered By: ntjess
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.