Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return key-value pair key based on key-value pair value date with sorting

I have the follow list:

test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'}, {'date': '2022-02-17 10:07:25', 'name': 'bar'}, {'date': '2022-02-18 04:00:05', 'name': 'baz'}]

I want to return the name attached to the most recent date. baz in this example. I probably need to use this but I don’t know how: .sort(key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'))

I tried something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sorted_list = test.sort(key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'))
print(sorted_list[0])

I read that list methods work in-place so i’m wondering how I can use it in my case.

>Solution :

You can simply do this

test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'}, {'date': '2021-02-19 10:07:25', 'name': 'bar'}, {'date': '2022-02-18 04:00:05', 'name': 'baz'}]
sortedList = sorted(test, key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'), reverse=True)
print(sortedList[0]['name'])

> baz
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading