Simon Leblanc
Simon Leblanc

Reputation: 1

Dictionary issue not returning a value Python

I am having a little problem accessing information inside an API generated dictionary. How would I access the date portion of the dictionary below? I am looking to return 2021-11-05 in the first entry.

urlDividend = ("https://.....")
stockDividend = get_jsonparsed_data(urlDividend)

date = stockDividend[0]["date"]
dividend = stockDividend[0]["dividend"]

I get an error (KeyError: 0) when I run those lines inside my code. Thanks for any help

{
  "symbol" : "AAPL",
  "historical" : [ {
    "date" : "2021-11-05",
    "label" : "November 05, 21",
    "adjDividend" : 0.2200000000,
    "dividend" : 0.22,
    "recordDate" : "2021-11-08",
    "paymentDate" : "2021-11-11",
    "declarationDate" : "2021-10-28"
  }, {
    "date" : "2021-08-06",
    "label" : "August 06, 21",
    "adjDividend" : 0.2200000000,
    "dividend" : 0.22,
    "recordDate" : "2021-08-09",
    "paymentDate" : "2021-08-12",
    "declarationDate" : "2021-07-27"
  }, {
    "date" : "2021-05-07",
    "label" : "May 07, 21",
    "adjDividend" : 0.2200000000,
    "dividend" : 0.22,
    "recordDate" : "2021-05-10",
    "paymentDate" : "2021-05-13",
    "declarationDate" : "2021-04-28"
  }, {
    "date" : "2021-02-05",
    "label" : "February 05, 21",
    "adjDividend" : 0.2050000000,
    "dividend" : 0.205,
    "recordDate" : "2021-02-08",
    "paymentDate" : "2021-02-11",
    "declarationDate" : "2021-01-27"
  }, {
    "date" : "2020-11-06",
    "label" : "November 06, 20",
    "adjDividend" : 0.2050000000,
    "dividend" : 0.205,
    "recordDate" : "2020-11-09",
    "paymentDate" : "2020-11-12",
    "declarationDate" : "2020-10-29"
  } ]
}

Upvotes: 0

Views: 61

Answers (2)

RossM
RossM

Reputation: 438

To access the dates, you need to get the data from the historical tag

You will need:

stockDividend["historical"][i]["date"]

Upvotes: 2

Matt
Matt

Reputation: 96

Looks like you need to look up the "historical" key first, the do [0]["date"] etc.

date = stockDividend["historical"][0]["date"]
dividend = stockDividend["historical"][0]["dividend"]

Looks like, overall, this is a dictionary object returned from get_jsonparsed_data.

Upvotes: 1

Related Questions