英文:
find oldest createdate and keyid from list of dicts and return result in a dict
问题
我从系统中得到以下响应:
{'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())
}
]
}
所以用户有两个不同的密钥,创建日期不同。
我需要从最旧的密钥中隔离出KeyId和CreateDate,并返回以下格式的字典:
{'KeyId': 'ABCDE12345', 'CreateDate': datetime.datetime(2022,11, 30, 13, 7, 43, tzinfo=tzutc())}
我似乎已经找到了至少获取最旧日期的方法:
mylist = my_result["KeyMetadata"]
seq = [x['CreateDate'] for x in mylist]
my_oldest = min(seq)
但接下来我该怎么做?如何获取相关的KeyId并构建字典响应?
英文:
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?
答案1
得分: 2
不要分离数据,使用自定义键min
来使用日期
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())}
英文:
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())}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论