Home > OS >  Accessing Values In Nested Dict In Python - String Indices Must Be Integers
Accessing Values In Nested Dict In Python - String Indices Must Be Integers

Time:04-29

I've gone through other similar problems here, but still can't identify my problem.

I have this JSON data returned from an API call:

{
  "Open": {
    "1638316800000": 120.5400009155,
    "1640995200000": 106.1399993896,
    "1643673600000": 67.2799987793,
    "1646092800000": 65.4300003052,
    "1648771200000": 50.1800003052,
    "1651104000000": 31.5699996948
  },
  "High": {
    "1638316800000": 126.75,
    "1640995200000": 106.8000030518,
    "1643673600000": 71.5,
    "1646092800000": 66.5400009155,
    "1648771200000": 50.2599983215,
    "1651104000000": 31.6900005341
  },
  "Low": {
    "1638316800000": 88.4000015259,
    "1640995200000": 50.0,
    "1643673600000": 53.5,
    "1646092800000": 33.4599990845,
    "1648771200000": 30.5799999237,
    "1651104000000": 30.5209999084
  },
  "Close": {
    "1638316800000": 103.6900024414,
    "1640995200000": 65.7399978638,
    "1643673600000": 67.5599975586,
    "1646092800000": 50.2400016785,
    "1648771200000": 31.2199993134,
    "1651104000000": 30.6100006104
  }
}

All I'm trying to do is assign the "Close" data to a new variable close and return close instead of the entire dictionary response.

Here is what I'm currently trying and I've tried different variations and all keep returning "string indices must be integers"

@app.route("/history")
def display_history():

    symbol = request.args.get('symbol', default="AAPL")
    period = request.args.get('period', default="1y")
    interval = request.args.get('interval', default="1mo")
    quote = yf.Ticker(symbol)
    hist = quote.history(period=period, interval=interval)
    data = hist.to_json()
    close = data["Close"]
    return close

CodePudding user response:

You are trying to use data, which is a string with json format, as your interpreter told you.

In order to read it as a dictionary with the key "Close", you can use the function loads from json package. It deserializes the string to a Python dictionary :

data = hist.to_json()
data = json.loads(data)
close = data["Close"]

Additionally, it appears that Ticker.history(), from yfinance module, returns a pandas Dataframe. If it is the case, you can use this instead :

data = hist.to_dict()
close = data['Close']

This way, the data is not converted to Json then back to Python dictionary again but straight to a dictionary.

  • Related