Home > Mobile >  How to target the keys in this object
How to target the keys in this object

Time:01-22

I have a function which makes an API request:

dates = []

def getIntraday():

    api_url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=TSCO.LON&outputsize=full&apikey=demo'

    r = requests.get(api_url)
    data = r.json()

    print(data)

getIntraday()

This returns something like:

{
  'Meta Data': {
    '1. Information': 'Daily Time Series with Splits and Dividend Events',
    '2. Symbol': 'TSCO.LON',
    '3. Last Refreshed': '2022-01-21',
    '4. Output Size': 'Full size',
    '5. Time Zone': 'US/Eastern'
  },
    'Time Series (Daily)': {
        '2022-01-21': {
        '1. open': '285.9',
        '2. high': '288.75',
        '3. low': '285.15',
        '4. close': '288.75',
        '5. adjusted close': '288.75',
        '6. volume': '14339516',
        '7. dividend amount': '0.0000',
        '8. split coefficient': '1.0'
        },
        '2022-01-20': {
        '1. open': '289.0',
        '2. high': '289.1',
        '3. low': '286.475',
        '4. close': '287.3',
        '5. adjusted close': '287.3',
        '6. volume': '15573050',
        '7. dividend amount': '0.0000',
        '8. split coefficient': '1.0'
        },
  }
}

my question is how do I get to the Time Series (Daily) object? Something like:

print(data[1])

Giving me:

'Time Series (Daily)': {
            '2022-01-21': {
            '1. open': '285.9',
            '2. high': '288.75',
            '3. low': '285.15',
            '4. close': '288.75',
            '5. adjusted close': '288.75',
            '6. volume': '14339516',
            '7. dividend amount': '0.0000',
            '8. split coefficient': '1.0'
            },
            '2022-01-20': {
            '1. open': '289.0',
            '2. high': '289.1',
            '3. low': '286.475',
            '4. close': '287.3',
            '5. adjusted close': '287.3',
            '6. volume': '15573050',
            '7. dividend amount': '0.0000',
            '8. split coefficient': '1.0'
            },

Here's my error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3356/3917313321.py in <module>
     10     print(data[1])
     11 
---> 12 getIntraday()

~\AppData\Local\Temp/ipykernel_3356/3917313321.py in getIntraday()
      8     data = r.json()
      9 
---> 10     print(data[1])
     11 
     12 getIntraday()

KeyError: 1

I need to compare high/low prices of a bunch of different times and I'm struggling to even be able to access the high low data in the object.

CodePudding user response:

You can access the part you want this way, and not by index (like you did in the code snippet)

...
data["Time Series (Daily)"]
...
  •  Tags:  
  • Related