2

After saving some data in a variable with cursor.fetchall(), it looks as follows:

mylist = [('abc1',), ('abc2',)] this is apparently a list.

That is not the issue.

The problem is that the following doesn't work:

if 'abc1' in mylist

it can't find 'abc1'. Is there a way in Python to do it easily or do I have to use a loop?

A I
  • 161
  • 6
  • 20
  • 2
    ``mylist`` is a list of tuples and ``'abc1'`` is a member of the tuple. ``'abc1' in mylist`` will be ``False`` because ``mylist`` has a _tuple_ ``('abc1',)`` – RedBaron Nov 30 '15 at 11:29

2 Answers2

0

fetchall() returns a row list, i.e., a list containing rows.

Each row is a tuple containing column values. There is a tuple even when there is only one column.

To check whether a row is in the row list, you have to check for the row instead of the column value alone:

if ('abc1',) in mylist
CL.
  • 173,858
  • 17
  • 217
  • 259
  • Oh man. I knew it was something that simple. My god I tried eth but didn't think of changing that criteria. Thank you! – A I Dec 01 '15 at 11:43
-1

This is problem with using select * statement.

Instead use select col1,col2 from table_name

Below code might help

sql = "select col1,col2,col3 from table_name"
cursor.execute(sql) # initialize cursor in your way
input_dict = dict( (row[0],(row[1],row[2])) for row in cursor.fetchall() )
Shrey
  • 1,242
  • 1
  • 13
  • 27