【问题标题】:Alpha Vantage for loop TypeError: string indices must be integers循环类型错误的 Alpha Vantage:字符串索引必须是整数
【发布时间】:2020-04-04 01:46:02
【问题描述】:

我一直在尝试让 for each 循环遍历数据并输出特定日期(例如 2020-04-03)的键和值。但我不断收到以下错误:TypeError: string indices must be integers

我的代码:

import time
from alpha_vantage.timeseries import TimeSeries
import json

key = 'Your key here'
ts = TimeSeries(key)
ko, meta = ts.get_daily(symbol='KO')

ko_info = json.dumps(ko, indent = 2, sort_keys = True)

data = json.loads(ko_info)

print(data)
print(type(data))

ko_org = json.dumps(data, indent = 2, sort_keys = True)
print(ko_org)
print(type(ko_org))

for x in ko_org['2020-04-01']:
    print(x['1. open'])

数据:

{
  "2019-11-11": {
    "1. open": "52.3300",
    "2. high": "52.3700",
    "3. low": "51.7750",
    "4. close": "51.8400",
    "5. volume": "8198125"
  },
  "2019-11-12": {
    "1. open": "51.9100",
    "2. high": "51.9100",
    "3. low": "51.5831",
    "4. close": "51.7100",
    "5. volume": "12656881"
  },
  "2019-11-13": {
    "1. open": "52.1800",
    "2. high": "52.4500",.....

【问题讨论】:

  • ko_org 是来自json.dumps 的字符串,而不是字典。你不能在这里做ko_org['2020-04-01']

标签: python json stockquotes alpha-vantage


【解决方案1】:

一些事情:

  1. python Alpha Vantage 包装器以 json 格式返回数据,因此无需这样做:
ko_info = json.dumps(ko, indent = 2, sort_keys = True)

data = json.loads(ko_info)

print(data)
print(type(data))

ko_org = json.dumps(data, indent = 2, sort_keys = True)
print(ko_org)
print(type(ko_org))

因为它是多余的,所以我们可以放弃所有这些。

  1. 正如@Psidom 所说,您不能像这样遍历一串 json.dumps,但是我们可以遍历从常规返回数据中获得的 dict/json,如下所示:
for x in ko:
    if x == '2020-04-01':
        print(ko[x])

这读作“对于返回的所有数据中的每个日期 x,如果日期 x 是 '2020-04-01',则打印该日期的报价”

我们把它们放在一起得到:

import time
from alpha_vantage.timeseries import TimeSeries

key = 'Your key here'
ts = TimeSeries(key)
ko, meta = ts.get_daily(symbol='KO')

for x in ko:
    if x == '2020-04-01':
        print(ko[x])

【讨论】:

    猜你喜欢
    • 2023-02-03
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2013-09-04
    • 2014-12-30
    • 2012-12-11
    • 2021-10-16
    相关资源
    最近更新 更多