yusuf
yusuf

Reputation: 3

Extracting the value from SQLite query as integer in Python

I made a SQLite query in Python like that:

SharesOwned = db.execute("SELECT SUM(Shares) FROM transactionTable WHERE Share='FB'")

print(SharesOwned)
if sharesOwned < sharesToSell:
    return errorMessage("You don't own that many shares of FB")

It prints:

[{'SUM(Shares)':10}]

Then it gives me this error:

TypeError: "List indices must be integers or slices not str"

How can I extract the number as an integer?

Upvotes: 0

Views: 1236

Answers (2)

Rehan Azher
Rehan Azher

Reputation: 1340

Try below changes : Update your query:

SELECT SUM(Shares) AS total FROM transactionTable WHERE Share='FB'

Then access SharedOwned:

if SharedOwned[0]['total']<sharesToSell:

Upvotes: 1

Stoicas
Stoicas

Reputation: 101

It looks like SharesOwned is a list of dictionaries. To return the number of shares you need to do the following in this particular case:

SharesOwned[0]['SUM(Shares)'] 

SharesOwned[0] accesses the first element of the list, in this case a dictionary {'SUM(Shares)':10}. Now you just need to lookup the value by key - 'SUM(Shares)' in this case.

Additionally, it looks like you have a typo in sharesOwned, s should be capitalized.

Upvotes: 2

Related Questions