Ualas Rohrer
Ualas Rohrer

Reputation: 67

Can't check if a value is within a list

I have this list that is the return of the rs = cur.fetchall and I can't find if the value 'type' inside it.

rs=[('objectid', 'integer'), ('nameshort', 'character varying'), ('urbanprojectyear', 'character varying'), ('urbanprojectname', 'character varying'), ('notes', 'character varying'), ('scalerank', 'smallint'), ('stylename', 'character varying'), ('firstyear', 'smallint'), ('lastyear', 'smallint'), ('type', 'character varying'), ('name', 'character varying'), ('globalid', 'character varying'), ('created_user', 'character varying'), ('created_date', 'timestamp without time zone'), ('last_edited_user', 'character varying'), ('last_edited_date', 'timestamp without time zone'), ('sde_state_id', 'bigint'), ('shape', 'USER-DEFINED')]

I've tried this and others several methods. But it always goes to the else of the if statement.

if 'type' in rs:
    print("True")
else: print("False")

What am I missing?

Upvotes: 1

Views: 55

Answers (3)

Raphael
Raphael

Reputation: 1801

rs is a list of tuples and 'type' is a string. A tuple is never equal to a string.

# check if 'type' is equal to the first value of any tuple
if 'type' in [t[0] for t in rs]:
    print("True")
else:
    print("False")

Upvotes: 1

Grismar
Grismar

Reputation: 31319

What you're missing is that 'type' is not in rs. However, ('type', 'character varying') is.

If you want to check if a tuple starting with 'type' is in the list, this would work:

print('type' in [x for x, _ in rs])

There's other, more efficient but wordier ways to solve the problem, but you get the idea.

In your case, the list really seems to be some representation of something that would be better as a dict. So, this is perhaps best for your case:

dict_rs = dict(rs)
print('type' in dict_rs)

Upvotes: 5

Kevin Welch
Kevin Welch

Reputation: 1508

This will not work because rs is nested.

A beginner friendly way is to do this is with a loop. You also get creative and one line it with list comprehensions, but I'll leave that to you.

found = False
for item in rs:
    if 'type' in item:
        found = True

if found:
    print('True')
else:
    print('False')

Upvotes: 1

Related Questions