IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 9: Flask › Data structure of a database query result in Flask: Exploring the datatype of the ‘portfolio’ variable”
- This topic is empty.
-
AuthorPosts
-
April 30, 2024 at 11:03 am #2351
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”sql” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
@app.route("/") @login_required def index(): """Show portfolio of stocks""" # Retrieve user's portfolio from the database portfolio = db.execute( "SELECT symbol, shares FROM portfolio WHERE user_id = ?", session["user_id"] )
[/dm_code_snippet]
Apparently, portfolio is a variable created that stores values retrieved from table portfolio. And that values stored in portfolio is in RAM. What is not clear is datatype of portfolio. Is it a list or a dictionary? Or something else?
ChatGPT:
In Flask, when you use
db.execute()
to fetch data from a database using SQL queries, the data retrieved is typically returned as a list of dictionaries.In your case, the
portfolio
variable would likely be a list where each element represents a row from the database result set. Each row is represented as a dictionary where the keys are the column names from the SQL query and the values are the corresponding values fetched from the database.Here’s an example of what the
portfolio
variable might look like:portfolio = [ {"symbol": "AAPL", "shares": 10}, {"symbol": "GOOGL", "shares": 5}, # Other rows... ]
In this example, each element in the
portfolio
list is a dictionary representing a row from the database. The keys are “symbol” and “shares”, which are the column names specified in the SQL query. The values are the actual values retrieved from the database.You can iterate over this list to access each row (which is a dictionary) and access specific columns using their keys. For example:
for stock in portfolio: print(stock["symbol"], stock["shares"])
This would print the symbol and shares for each stock in the portfolio.
-
AuthorPosts
- You must be logged in to reply to this topic.