Ahijit
Ahijit

Reputation: 134

How to access each element of a sql query returned to python?

The stock returns the stocks owned by the user. I want to pass a function lookup() on each stock returned to get the price of the stock. How will I do it since the query returns multiple rows?

rows = "SELECT * FROM :p1 ORDER BY id"
db.execute(rows,{'p1':str(session['user_id'])})
rows = db.fetchall()
stock = rows[0]['symbol']
share = rows[0]['shares']
price = []

Upvotes: 0

Views: 413

Answers (1)

Mike
Mike

Reputation: 2614

Hard to say if this is what you're looking for but sounds like you're looking for a way to search a list of dictionaries.

>>> rows = [{'symbol': 'APPL', 'shares':1000},{'symbol': 'GE', 'shares': 2000},{'symbol': 'TWTR', 'shares': 5000}]
>>> def lookup(rows, stock):
...    results = [row for row in rows if row["symbol"] == stock]
...    return results
... 
>>> lookup(rows, 'APPL')
[{'symbol': 'APPL', 'shares': 1000}]

Upvotes: 1

Related Questions