python列表获取最后一项_python:从列表中获取最后一个匹配字典

@亚维克

,您可以尝试下面的代码。

我用过

筛选器()

函数筛选具有特定键的词典。

def get_last_dict_with_specific_id(test_dict, id):

# Create tasks list from test_dict

tasks = test_dict["tasks"]

# filter tasks list based on dictionaries id i.e get a list of dictionaries with only specific id

# Update the same list tasks with different content (save space)

tasks = [d for d in tasks if d["id"] == id]

# tasks = filter(lambda d: d["id"] == id, tasks) # This is efficient like above one

# Pick the last dictionary and return it

if tasks:

return tasks[len(tasks) - 1]

else:

return {}

# TEST

test_dict = {'user': 'xxx','tasks': [{'id':'01','age':'60'},{'id':'02','age':'50'},{'id':'01','age':'65'},{'id':'02','age':'65'}]};

last_dict_01 = get_last_dict_with_specific_id(test_dict, '01');

print last_dict_01; # {'age': '65', 'id': '01'}

last_dict_02 = get_last_dict_with_specific_id(test_dict, '02');

print last_dict_02; # {'age': '65', 'id': '02'}

last_dict_03 = get_last_dict_with_specific_id(test_dict, '03');

print last_dict_03; # {}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值