Home > database >  find oldest createdate and keyid from list of dicts and return result in a dict
find oldest createdate and keyid from list of dicts and return result in a dict

Time:01-08

I get below response from a system:

{'KeyMetadata':
[
    {
        'UserName': 'thisusernameA',
        'KeyId': 'ABCDE12345',
        'CreateDate': datetime.datetime(2022,11, 30, 13, 7, 43, tzinfo=tzutc())
    },
    {
        'UserName': 'thisusernameA',
        'KeyId': 'CDEFG678911',
        'CreateDate': datetime.datetime(2022,12, 9, 14, 50, 36, tzinfo=tzutc())
    }
]
}

so the user has two different keys, with a different createdate. I have to isolate the KeyId and CreateDate from the oldest key, and return the result in a dict like this:

{'KeyId': 'ABCDE12345', 'CreateDate': datetime.datetime(2022,11, 30, 13, 7, 43, tzinfo=tzutc())}

I seems that I have figured out a way to at least get the oldest date:

mylist=my_result["KeyMetadata"]
seq = [x['CreateDate'] for x in mylist]
my_oldest=min(seq)

But what do I do next? how do I get the relating KeyId and construct a dict response?

CodePudding user response:

Don't separate the data, use min with a custom key to use the date

data = {'KeyMetadata': [
    {'UserName': 'thisusernameA', 'KeyId': 'ABCDE12345',
     'CreateDate': datetime.datetime(2022, 11, 30, 13, 7, 43, tzinfo=tzutc())},
    {'UserName': 'thisusernameA', 'KeyId': 'CDEFG678911',
     'CreateDate': datetime.datetime(2022, 12, 9, 14, 50, 36, tzinfo=tzutc())}
]}

min_item = min(data['KeyMetadata'], key=lambda item: item['CreateDate'])
print(min_item)
# {'UserName': 'thisusernameA', 'KeyId': 'ABCDE12345', 'CreateDate': datetime.datetime(2022, 11, 30, 13, 7, 43, tzinfo=tzutc())}
  • Related