1

I am trying to retrieve some data from a table and output it as a list. The problem is that the resulting list is not in the correct form.

This is my table: enter image description here

My code:

cur.execute("SELECT tegebruikentags FROM tagstegebruiken WHERE wel_niet_lezen = True")
taglist = cur.fetchall()
print (taglist)

The output:

[('Bakkerij.Device1.DB100INT0',), ('Bakkerij.Device1.DB100INT4',), ('Bakkerij.Device1.DB100INT8',)]

The desired output:

['Bakkerij.Device1.DB100INT0', 'Bakkerij.Device1.DB100INT4', 'Bakkerij.Device1.DB100INT8']

How should I edit the code in order to get the list as I want?

Thanks in advance!

RobbeM
  • 727
  • 7
  • 16
  • 36

2 Answers2

2

I'm not sure if you can do this automatically with the query, but this is a solution.

li = [item[0] for item in cur.fetchall()]
print li
'['Bakkerij.Device1.DB100INT0', 'Bakkerij.Device1.DB100INT4', 'Bakkerij.Device1.DB100INT8']'
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

If you are using psycopg2 , cursor.fetchall returns a list of tuples, even if there is only a single column in it.

You can convert that list of tuples to a list using -

taglist = [i for item in taglist for i in item]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176