Single column fetch returning in list in python postgresql
Question:
Database:
id
trade
token
1
abc
5523
2
fdfd
5145
3
sdfd
2899
Code:
def db_fetchquery(sql):
conn = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432')
cursor = conn.cursor()
conn.autocommit = True
cursor.execute(sql)
row = cursor.rowcount
if row >= 1:
data = cursor.fetchall()
conn.close()
return data
conn.close()
return False
print(db_fetchquery("SELECT token FROM script"))
Result:
[(5523,),(5145,),(2899,)]
But I need results as:
[5523,5145,2899]
I also tried print(db_fetchquery("SELECT zerodha FROM script")[0])
but this gave result as:- [(5523,)]
Also, why is there ‘,’ / list inside list when I am fetching only one column?
Answers:
Not sure if you are able to do that without further processing but I would do it like this:
data = [x[0] for x in data]
which convert the list of tuples to a 1D list
To convert [(5523,),(5145,),(2899,)]
to [5523, 5145, 2899]
you can use lambda or list comprehension
using lambda
res = [(5523,),(5145,),(2899,)]
res = list(map(lambda x: x[0], res))
print(res)
#output: [5523, 5145, 2899]
using list comprehension
res = [(5523,),(5145,),(2899,)]
res = [i[0] for i in res]
print(res)
#output: [5523, 5145, 2899]
Database:
id | trade | token |
---|---|---|
1 | abc | 5523 |
2 | fdfd | 5145 |
3 | sdfd | 2899 |
Code:
def db_fetchquery(sql):
conn = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432')
cursor = conn.cursor()
conn.autocommit = True
cursor.execute(sql)
row = cursor.rowcount
if row >= 1:
data = cursor.fetchall()
conn.close()
return data
conn.close()
return False
print(db_fetchquery("SELECT token FROM script"))
Result:
[(5523,),(5145,),(2899,)]
But I need results as:
[5523,5145,2899]
I also tried print(db_fetchquery("SELECT zerodha FROM script")[0])
but this gave result as:- [(5523,)]
Also, why is there ‘,’ / list inside list when I am fetching only one column?
Not sure if you are able to do that without further processing but I would do it like this:
data = [x[0] for x in data]
which convert the list of tuples to a 1D list
To convert [(5523,),(5145,),(2899,)]
to [5523, 5145, 2899]
you can use lambda or list comprehension
using lambda
res = [(5523,),(5145,),(2899,)]
res = list(map(lambda x: x[0], res))
print(res)
#output: [5523, 5145, 2899]
using list comprehension
res = [(5523,),(5145,),(2899,)]
res = [i[0] for i in res]
print(res)
#output: [5523, 5145, 2899]