【问题标题】:How to pull values from a dictionary with in a list? Specifically the first dictionary如何从列表中的字典中提取值?特别是第一本词典
【发布时间】:2021-12-28 17:05:23
【问题描述】:

所以我试图从包含大量字典的列表中提取数据。特别是 仅限第一个字典中的键:值对。例如,最终目标是将 'symbol' 保存到变量中,如果可能的话,将 'AAPL' 保存到变量中。 这是我到目前为止拉整个列表的代码:

from urllib.request import urlopen
import json

with urlopen("https://financialmodelingprep.com/api/v3/ratios/AAPL?apikey=MYAPIKEY") as response:
    source = response.read()
    data = json.loads(source)
    data2 = json.dumps(data, indent=4)
    print(data2) 

上面的代码打印以下内容(实际输出的较小版本):

[
    {
        "symbol": "AAPL",
        "date": "2021-09-25",
        "period": "FY",
        "currentRatio": 1.0745531195957954,
        "quickRatio": 0.9096596297447422,
        "cashRatio": 0.2784485300563432
    },
    {
        "symbol": "AAPL",
        "date": "2020-09-26",
        "period": "FY",
        "currentRatio": 1.3636044481554577,
        "quickRatio": 1.2181949294064065,
        "cashRatio": 0.36071049035979963
    },
    {
        "symbol": "AAPL",
        "date": "2019-09-28",
        "period": "FY",
        "currentRatio": 1.540125617208044,
        "quickRatio": 1.3844473032028604,
        "cashRatio": 0.46202160464632325
    }
]

每本词典代表公司的不同年份。

如果我想提取第一个 key:value 对,我该怎么做?

我尝试过使用[d['symbol'] for d in data2],但我得到了TypeError: string indices must be integers 我也尝试过使用[d[0:1] for d in data2] 对其进行切片,但它会返回像['[', '\n', ' ', ' ', ' ', ' ', '{', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '"', 's', 'y', 'm', 'b', 'o', 'l' 这样的单个字符

我一直在绞尽脑汁想要得到这个,但不知道还能尝试什么。谢谢。

【问题讨论】:

  • [d['symbol'] for d in data2] 适用于您的示例数据。
  • data2 是一个 JSON 字符串。你应该使用data
  • data2 是一个字符串,对数据使用相同的东西
  • 你可以做key, value = data [0].items()[0]。它会给你"symbol","AAPL". 这确实依赖于符号始终是第一个键。 Python 字典是按输入顺序排列的(从 3.5 左右开始),因此如果您在将 data 从 JSON 转换后对其进行操作,则顺序可能不会保持不变。

标签: python list dictionary


【解决方案1】:

data2 是一个字符串,这就是为什么切片它会返回单个字符。

要访问列表中的第一个字典,请使用data[0]

要访问该字典中的键,请使用 data[0]['symbol']data[0]['date'] 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 2020-11-10
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多