Home > Blockchain >  How to pull values from a dictionary with in a list? Specifically the first dictionary
How to pull values from a dictionary with in a list? Specifically the first dictionary

Time:12-29

so I'm attempting to pull data from a list that contains numerous dictionaries. Specifically both the key:value pair from the first dictionary only. End goal is to save, for example, 'symbol' to a variable and 'AAPL' to a variable, if possible. Here is the code I have so far to pull the entire list:

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) 

The code above prints the following (smaller version of actual output):

[
    {
        "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
    }
]

Each dictionary represents a different year for the company.

If I wanted to pull the first key:value pair, how can I accomplish that?

I've tried using [d['symbol'] for d in data2] but I get TypeError: string indices must be integers I've also tried slicing through it by using [d[0:1] for d in data2] but it's returning single characters like ['[', '\n', ' ', ' ', ' ', ' ', '{', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '"', 's', 'y', 'm', 'b', 'o', 'l'

I've been racking my brain trying to get this and not sure what else to try. Thanks.

CodePudding user response:

data2 is a string, which is why slicing it returns single characters.

To access the first dictionary in the list, use data[0].

To access keys in that dictionary, use data[0]['symbol'], data[0]['date'], etc.

  • Related