Reputation: 1169
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?
Upvotes: 1
Views: 21706
Reputation: 2801
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
Upvotes: 7
Reputation: 1450
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
Upvotes: 0
Reputation: 5205
>>> 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
.
Upvotes: 2
Reputation: 32502
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:
Upvotes: 1
Reputation: 350
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()]
Upvotes: 0
Reputation: 2164
>>> listofpeople = [{'Jack': ['Blue', 'Red', 'Green']}, {'Barry': ['Red', 'Green', 'Orange']}]
>>> [i for i, d in enumerate(listofpeople) if "Jack" in d.keys()]
[0]
Upvotes: 6
Reputation: 788
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
Upvotes: 0
Reputation: 1153
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
Upvotes: 0