Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:从列表中获取最后一个匹配的字典_Python_Python 2.7_List_Dictionary_Iteration - Fatal编程技术网

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

python:从列表中获取最后一个匹配的字典,python,python-2.7,list,dictionary,iteration,Python,Python 2.7,List,Dictionary,Iteration,如何从字典列表中获取最后一个匹配的字典: 例如: test_dict={'user'='xxx','tasks':[{'id':'01','age':'60'},{'id':'02','age':'50'},{'id':'01','age':'65'},{'id':'02','age':'65'}]} 如何从“id”为“01”的任务中获取最后一个dict 我需要遍历整个列表-test_dict['tasks']吗?或者有什么好方法吗 谢谢这应该符合你的目的 test_dict={'user':

如何从字典列表中获取最后一个匹配的字典:

例如:

test_dict={'user'='xxx','tasks':[{'id':'01','age':'60'},{'id':'02','age':'50'},{'id':'01','age':'65'},{'id':'02','age':'65'}]}
如何从“id”为“01”的任务中获取最后一个dict

我需要遍历整个列表-test_dict['tasks']吗?或者有什么好方法吗


谢谢

这应该符合你的目的

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

id_key = '01'

id_value = {}

tasks = test_dict['tasks']

for i in reversed(tasks):
    if(i['id'] == id_key):
        id_value = i
        break;


print "Found key"      
print id_value

您可以将
next
与反向迭代列表的生成器表达式一起使用。如果未找到匹配项,函数将返回
None

def get_last(d, val):
    return next((i for i in reversed(d['tasks']) if i['id'] == val), None)

res = get_last(test_dict, '01')

print(res)

{'id': '01', 'age': '65'}

@Aavik,您可以尝试以下代码

我使用了filter()函数来过滤带有特定键的词典

在线尝试代码(使用filter()函数效率较低)

还可以尝试(使用列表理解,这是一种有效的方法)


你至少应该向我们展示你迄今为止的尝试以及失败的原因。提示:向后看列表。处理缺失值。您应该考虑使用列表理解而不是<代码>过滤器>代码> +>代码> lambda < /Cord>。它更高效(可以说)更可读。
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;  # {}