3

I'm attempting to retrieve data from within a nested JSON data using Python.

Abbreviated example of the JSON data:

{

    "daily" : {
        "1524182400000" : 438,
        "1524268800000" : 438,
        "1524355200000" : 437,
        "1524441600000" : 437,
        "1524528000000" : 432
    }
}

As you see, each of the above keys is a unix timestamp and the overall object is constantly updated with new key/value pairs.

While I am easily able to retrieve the data if I know the timestamp I don't know how I get the value of the latest timestamp.

I would usually complete this in PHP with the below code and selecting the array position:

foreach ($data["daily"] as $timedate => $value) {
    array_push($ValueArray, $value);
    array_push($ValueDate, $timedate);
}

How do I get this in Python?

Any help would be appreciated!

1
  • so you want to grab the last key in the nested dictionary? Commented Apr 24, 2018 at 18:47

3 Answers 3

4

The entry you're looking for is prices['daily'][max(prices['daily'], key=int)].

max(prices['daily'], key=int) iterates over the keys and find the largest (aka, most recent) one. Setting key=int ensures the function does a numerical, rather than lexical comparison.

Sign up to request clarification or add additional context in comments.

Comments

0

just use the equivalent of foreach in python:

for timedate, value in tmp['daily'].items():
    # Do something with timedate or value...

It works exactly like the foreach on php.

Comments

0

For what you are loking for, this will work:

json_data['daily'][sorted(json_data['daily'].keys())[-1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.