Reputation: 867
I have three Python dictionaries like so:
dict_1 = {
'Id':'001',
'CreatedDate':'2017-04-24T06:49:28.000Z',
'FirstName':'R',
'LastName':'Hendrix',
'Company':'Hooli',
'Age':29
}
dict_2 = {
'Id':'002',
'CreatedDate':'2010-01-23T06:49:28.000Z',
'FirstName':'Richard',
'LastName':'Hendricks',
'Company':'Pied Piper',
'Age':30
}
dict_3 = {
'Id':'003',
'CreatedDate':'2013-01-23T06:49:28.000Z',
'FirstName':'Richard',
'LastName':'Hendricks',
'Company':'Pied Piper',
'Age':31
}
I want to create functions to get the newest or oldest values from these dictionaries based on the CreatedDate
value.
I imagine I would need to put all of these dicts in a list:
list_of_dicts = [dict_1, dict_2, dict_3]
An function might work like so:
def get_newest(
list_of_dicts,
created_date_fieldname='CreatedDate',
return_field='Company'
):
# TODO - take in two or more dicts, and return the newest Company
# value based on CreatedDate field.
Upvotes: 0
Views: 147
Reputation: 176
You can use max and min built-in function.
>>> from datetime import datetime
>>> def get_newest(list_of_dicts, created_date_fieldname='CreatedDate', return_field='Company'):
... return max(list_of_dicts, key=lambda x: datetime.strptime(x[created_date_fieldname], "%Y-%m-%dT%H:%M:%S.%fZ"))[return_field]
...
>>> print get_newest(list_of_dicts)
Hooli
Upvotes: 0
Reputation: 26207
You could use datetime.strptime()
to parse the dates, then after that you just compare them until you've found the newest date.
from datetime import datetime
def get_newest(list_of_dicts, created_date_fieldname='CreatedDate', return_field='Company'):
if not list_of_dicts:
return None
newest = list_of_dicts[0]
for current in list_of_dicts:
newest_date = datetime.strptime(newest[created_date_fieldname], "%Y-%m-%dT%H:%M:%S.%fZ")
current_date = datetime.strptime(current[created_date_fieldname], "%Y-%m-%dT%H:%M:%S.%fZ")
if current_date >= newest_date:
newest = current
return newest[return_field]
Now doing print(get_newest(list_of_dicts))
(given your data) would output:
Hooli
Note that if there's multiple instances of the newest date. Then the last instance will be selected. If you instead what the first instance, then use current_date > newest_date
instead.
Upvotes: 1