如何从Python字典列表中获取满足双条件的mailingListId
解决方法:先筛选再取最大值
嘿,你只需要在取最大值之前,先把符合name前缀条件的条目过滤出来就行啦!这里给你几种实现方式,按需选择:
分步实现(可读性更强)
先缩小范围到所有name以NIP开头的字典,再在这个子集里找creationDate最大的条目:
data = [{'contactCount': 0, 'creationDate': 1581004876000, 'lastModifiedDate': 1581004876000, 'mailingListId': 'ML1010', 'name': 'NIP_2020-02-06', 'ownerId': 'GR_AB'}, {'contactCount': 0, 'creationDate': 1581004875000, 'lastModifiedDate': 1581004875000, 'mailingListId': 'ML1011', 'name': 'NH_2020-02-06', 'ownerId': 'GR_AB'}, {'contactCount': 0, 'creationDate': 1581004874000, 'lastModifiedDate': 1581004874000, 'mailingListId': 'ML1012', 'name': 'LH_2020-02-06', 'ownerId': 'GR_AB'}, {'contactCount': 0, 'creationDate': 1580942151000, 'lastModifiedDate': 1580942151000, 'mailingListId': 'ML1013', 'name': 'NIP_2020-02-05', 'ownerId': 'GR_AB'}, {'contactCount': 0, 'creationDate': 1580942151000, 'lastModifiedDate': 1580942151000, 'mailingListId': 'ML1014', 'name': 'NH_2020-02-05', 'ownerId': 'GR_AB'}, {'contactCount': 0, 'creationDate': 1580942151000, 'lastModifiedDate': 1580942151000, 'mailingListId': 'ML1015', 'name': 'LH_2020-02-05', 'ownerId': 'GR_AB'}, {'contactCount': 5, 'creationDate': 1580496243000, 'lastModifiedDate': 1580496295000, 'mailingListId': 'ML1016', 'name': 'NIP_2020-02-01', 'ownerId': 'GR_AB'}] # 1. 过滤出name以"NIP"开头的条目 filtered_data = [item for item in data if item['name'].startswith('NIP')] # 2. 在过滤后的列表中找到creationDate最大的条目 target_item = max(filtered_data, key=lambda x: x['creationDate']) # 3. 提取对应的mailingListId mailingListId = target_item['mailingListId'] print(mailingListId) # 输出结果:ML1010
一行代码实现(更简洁)
用生成器表达式代替列表推导式,直接在max函数里完成过滤,节省内存(尤其适合数据量很大的场景):
mailingListId = max((item for item in data if item['name'].startswith('NIP')), key=lambda x: x['creationDate'])['mailingListId']
健壮性优化(处理无匹配的情况)
如果担心没有符合条件的条目导致max报错,可以加个判断逻辑:
filtered_data = [item for item in data if item['name'].startswith('NIP')] if filtered_data: mailingListId = max(filtered_data, key=lambda x: x['creationDate'])['mailingListId'] else: mailingListId = None # 或者根据业务需求返回默认值、抛出提示等
内容的提问来源于stack exchange,提问作者Mohammed Khan
相关产品推荐
相关产品推荐

