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

时间:2016-03-03 17:11:01

标签: python string dictionary

我能够使用谷歌api融资,但它今天停止工作,所以我被迫寻找替代方案。

我正在尝试实施Google财经模块,以下是我的尝试

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)

2 个答案:

答案 0 :(得分:0)

我假设getQuotes返回一个包含一个字典的列表。如果你想获得没有列表的字典,那么使用索引来提取它:

my_dict = getQuotes('YHOO')[0]

答案 1 :(得分:0)

由于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]

同样的效果。

相关问题