将字符串转换为给定python输出格式的字典

2024-04-19 20:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用谷歌api财务,但它今天停止工作,所以我不得不找到一个替代品。你知道吗

我正在尝试实现谷歌财务模块,下面是我的尝试

from googlefinance import getQuotes
import json
import time
import ast  

y = json.dumps(getQuotes('YHOO'), indent=2)

print y
print type(y)
print len(y)
price = y[275]
print price



##where i wanna be able to update the stock price 
#while True:

    #time.sleep(3)

然后我得到以下输出

[
  {
    "Index": "NASDAQ", 
    "LastTradeWithCurrency": "32.58", 
    "LastTradeDateTime": "2016-03-03T11:54:19Z", 
    "LastTradePrice": "32.58", 
    "LastTradeTime": "11:54AM EST", 
    "LastTradeDateTimeLong": "Mar 3, 11:54AM EST", 
    "StockSymbol": "YHOO", 
    "ID": "658890"
  }
]
<type 'str'>
292
[

我知道,如果我把它切成y= y[1:len(y)-1],去掉原始输出的[],它就是dict格式的。
不知道从这里到哪里去。(我知道,如果我只是在切片后复制输出并将其赋给一个新变量,它就会存储为dict)


Tags: 模块importapijson替代品lentimetype
2条回答

因为getQotes()返回一个list,里面有一个dict,所以没有理由先jsonify它。你知道吗

from googlefinance import getQuotes
import json

yhoo = getQuotes('YHOO')[0]
jsonyhoo = json.dumps(yhoo, indent=2)
assert type(yhoo) is dict
assert type(jsonyhoo) is str

作为旁白,你不需要跑:

someString[1:len(someString)-1]

您可以简单地执行以下操作:

someString[1:-1]

同样的效果。你知道吗

我假设getQuotes返回一个列表,其中包含一个字典项。如果只想获取没有列表的词典,请使用索引将其提取:

my_dict = getQuotes('YHOO')[0]

相关问题 更多 >