Gil
Gil

Reputation: 962

python syntax error with list filtering

I'm trying to filter an item from a list, and I'm getting a syntax error: SyntaxError: invalid syntax

The code:

a['name'] = 'Dan'
b['name'] = 'Joe'

ppl = [a,b]
inputName = raw_input('Enter name:').strip()
person = [p in ppl if p['name']==inputName].pop()

any idea?

Upvotes: 2

Views: 1142

Answers (3)

Morten Jensen
Morten Jensen

Reputation: 5936

I agree with Bogna Anna Ka, use a dictionary.

This is a bit more pythonic in my opinion:

a = {'name':'Dan'}
b = {'name':'Joe'}
ppl = [a,b]
for key, value in ppl.iteritems()
    if(key == inputName):
        person = value

You iterate over the key-value pairs instead of creating a list of keys and iterating over them (which for p in ppl: implicitly does) and doing the get(), pop() and index()

Upvotes: 0

bognix
bognix

Reputation: 211

First of all, you should use dictionary instead of list if you want to use 'name' key. It should look like this

    a = {'name':'Dan'}
    b = {'name':'Joe'}
    ppl = [a,b]
    for p in ppl:
        if(p['name']==inputName):
            person=ppl.pop(ppl.index(p))

Maybe there is a better way, more pythonic, but this one working ;)

Upvotes: 1

Marcus
Marcus

Reputation: 6849

[item for item in array] not [item in array]

Upvotes: 8

Related Questions