Retrieve value of last key in dictionary
<p>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. </p>

<p>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. </p>

<p>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. </p>

<p>So how would I go about retrieving the value of the last key in the dictionary?</p>

<p>Here is an example of what the JSON object looks like: </p>

<pre><code>{'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} 
</code></pre>

<p>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 <code>k,v = max(data.items())</code> 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.</p>

<hr>

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

<pre><code>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
</code></pre>

python sorting dictionary key key-value