'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:
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 1:[1]
Try this one
from datetime import datetime
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'}]
sorted_list = sorted(test, key=lambda d: datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S'), reverse=True)
print(sorted_list[0])
Output:
{'date': '2022-02-18 04:00:05', 'name': 'baz'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | krishna |
