Marty Wallace
Marty Wallace

Reputation: 35754

python - access list element by key

If I have the following structure:

[
    {'id' : 100, 'name' : 'Bill'},
    {'id' : 100, 'name' : 'Dave'}
]

How can I get an element by the 'name' key. That is, I want to get {'id' : 100, 'name' : 'Dave'}but without having to iterate and check each for a match.

Is this possible and if so how?

Upvotes: 2

Views: 23311

Answers (2)

zenpoy
zenpoy

Reputation: 20126

This is what you are looking for

[x for x in a if x['name']=='Dave']

But here you are iterating over the list and checking each item. Actually, there's no way to do such a thing without iterating over the list, because it's a list and not a map.

Upvotes: 0

JBernardo
JBernardo

Reputation: 33407

You can first transform your list of dictionaries into a single dictionary with "name" as the key:

data = {x['name']: x for x in original_data}

Then you use:

data['Dave']
data['Bill']

PS: For Python older than 2.7, use this:

data = dict((x['name'], x) for x in original_data)

Upvotes: 8

Related Questions