[英]Extracting the value from SQLite query as integer in Python
I made a SQLite query in Python like that: 我在Python中像这样进行了SQLite查询:
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? 如何将数字提取为整数?
It looks like SharesOwned is a list of dictionaries. 看起来SharesOwned是词典列表。 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}. SharesOwned [0]访问列表的第一个元素,在本例中为字典{'SUM(Shares)':10}。 Now you just need to lookup the value by key - 'SUM(Shares)' in this case.
现在,在这种情况下,您只需要通过键-'SUM(Shares)'查找值。
Additionally, it looks like you have a typo in sharesOwned, s should be capitalized. 此外,看起来您在shareOwned中有错字,应该将s大写。
Try below changes : Update your query: 尝试以下更改:更新查询:
SELECT SUM(Shares) AS total FROM transactionTable WHERE Share='FB'
Then access SharedOwned: 然后访问SharedOwned:
if SharedOwned[0]['total']<sharesToSell:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.