Naaah Naaah - 3 months ago 9
Python Question

Retrieve value of last key in dictionary

I'm trying to extract financial figures from an API that returns a JSON object. The API does not explicitly state that the dictionaries returned are OrderedDicts however the output is always sorted thus I'm going to make the assumption that it is.

I need to retrieve the value of the last key in the dictionary as I need the most current financial figures. However I cannot explicitly use the name of the key to extract it as it is in a date format and may be different depending on the company using queried.

I tried to convert the dictionary object into a list and select the last key using an index of -1 however the conversion process seems to randomize the order of the dictionary no longer retrieves the last date.

So how would I go about retrieving the value of the last key in the dictionary?

Here is an example of what the JSON object looks like:

{'2007-06-01T00:00:00': 21.19,
'2008-06-01T00:00:00': 26.01,
'2009-06-01T00:00:00': 19.34,
'2010-06-01T00:00:00': 22.88,
'2011-06-01T00:00:00': 23.77,
'2012-06-01T00:00:00': 14.77,
'2013-06-01T00:00:00': 16.58,
'2014-06-01T00:00:00': 14.02,
'2015-06-01T00:00:00': 7.0,
'2016-06-01T00:00:00': 9.08}

Answer

After reconsidering the problem I realize that because the date is in a format that they are correctly comparable as strings, you can just do k,v = max(data.items()) however if you (or someone else looking at this thread) uses a date format that doesn't work like that my original answer is below.


you can simply use the max builtin to compare the keys of the dictionary, to make sure they are all compared as dates and times you can use the key argument to compare them as datetime objects:

import datetime

data = {'2007-06-01T00:00:00': 21.19,
 '2008-06-01T00:00:00': 26.01,
  '2009-06-01T00:00:00': 19.34,
  '2010-06-01T00:00:00': 22.88,
  '2011-06-01T00:00:00': 23.77,
  '2012-06-01T00:00:00': 14.77,
  '2013-06-01T00:00:00': 16.58,
  '2014-06-01T00:00:00': 14.02,
  '2015-06-01T00:00:00': 7.0,
  '2016-06-01T00:00:00': 9.08}

def converter(timestamp):
    return datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")

highest = max(data.keys(),key=converter)

print(highest) #2016-06-01T00:00:00
Comments