简体   繁体   English

检索字典中最后一个键的值

[英]Retrieve value of last key in dictionary

I'm trying to extract financial figures from an API that returns a JSON object. 我正在尝试从返回JSON对象的API中提取财务数据。 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. API没有明确指出返回的字典是OrderedDicts,但是输出始终进行排序,因此我将假设它是。

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. 我试图将字典对象转换为列表,并使用索引-1选择最后一个键,但是转换过程似乎随机化了字典的顺序,不再获取最后一个日期。

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: 这是JSON对象的示例:

{'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} 

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. 重新考虑问题后,我意识到,由于日期采用的格式可以正确地与字符串进行比较,因此可以执行k,v = max(data.items())但是如果您(或其他正在查看此线程的人)使用的日期格式无法正常显示以下原始答案。


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: 您可以简单地使用max内置函数来比较字典的键,以确保它们都被比较为日期和时间,您可以使用key参数将它们作为datetime对象进行比较:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM