简体   繁体   English

如何在具有混合类型值的字典中获取具有最大日期值的项目?

[英]How to get the item with max date value in a dictionary with mixed type values?

In the dictionary a :在词典中a

from datetime import datetime

a = {"ID":3, "CITY":"ATLANTIS", "FOUNDATION":datetime(2014,10,12), "COLLAPSE":datetime(2010,10,12), "REGENERATE":datetime(2011,10,12)}

How would you get the value which has the oldest date in this dictionary (in this case "COLLAPSE":datetime(2010,10,12) )?您将如何获得该字典中日期最早的值(在本例中为"COLLAPSE":datetime(2010,10,12) )? Remember, not all values are of same data type.请记住,并非所有值都具有相同的数据类型。

If you wanted the earliest date, you want to use min() , not max() here;如果你想要最早的日期,你想在这里使用min() ,而不是max() a datetime earlier in time sorts before another that is later.时间较早的日期时间排在较晚的日期时间之前。

You'd need to use a custom key callable here, and return datetime.max for any value that is not a datetime object to discount that key:您需要在此处使用可调用的自定义key ,并为不是datetime对象的任何值返回datetime.max以打折该键:

from datetime import datetime

min(a.iteritems(),
    key=lambda i: i[1] if isinstance(i[1], datetime) else datetime.max)

This returns both the key and the value.这将返回键和值。

To get just the key, use:要获取密钥,请使用:

min(a, key=lambda k: a[k] if isinstance(a[k], datetime) else datetime.max)

and for just the value:仅就价值而言:

min(a.itervalues(),
    key=lambda v: v if isinstance(v, datetime) else datetime.max)

In all cases only the exact syntax to get the value to compare differs.在所有情况下,只有获取要比较的值的确切语法不同。

Demo:演示:

>>> from datetime import datetime
>>> a = {"ID":3, "CITY":"ATLANTIS", "FOUNDATION":datetime(2014,10,12), "COLLAPSE":datetime(2010,10,12), "REGENERATE":datetime(2011,10,12)}
>>> min(a.iteritems(),
...     key=lambda i: i[1] if isinstance(i[1], datetime) else datetime.max)
('COLLAPSE', datetime.datetime(2010, 10, 12, 0, 0))
>>> min(a, key=lambda k: a[k] if isinstance(a[k], datetime) else datetime.max)
'COLLAPSE'
>>> min(a.itervalues(),
...     key=lambda v: v if isinstance(v, datetime) else datetime.max)
datetime.datetime(2010, 10, 12, 0, 0)

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

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