Home > database >  return key-value pair key based on key-value pair value date with sorting
return key-value pair key based on key-value pair value date with sorting

Time:02-25

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.

CodePudding user response:

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

CodePudding user response:

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'}
  • Related