1

I am using psycopg2 to do a psql query.

cur.execute("SELECT DISTINCT name FROM product")
result = cur.fetchall()
print(result)

[('product1',), ('product2',), ('product3',), ('product4',)]

I need to reformat this array to make an API endpoint. Right now it is a list of tuples where the second value of the tuple is empty. A simple loop iterating through gets the job done.

results=[]
for item in result:
    results.append(item[0])
print(results)

['product1','product2','product3','product4']

However this query can get rather large. And iterating through the entire list adds a delay to the query that doesn't seem necessary. Is there a way to flatten the array in constant time, or a differnt psycopg2 function that returns in the format I need?

2 Answers 2

2

The time needed to convert the list is negligible compared to the database query. But you don't need to create a list first-hand:

cur.execute("SELECT DISTINCT name FROM product")
result = [item for item, in cur]
print(result) 
Sign up to request clarification or add additional context in comments.

Comments

1

Aggregate in the query:

query = '''
    select array_agg(distinct name)
    from product
'''
cursor.execute(query)
rs = cursor.fetchall()[0][0]
print rs

Output:

['product1', 'product2', 'product3', 'product4']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.