@Aavik vous pouvez essayer le code ci-dessous.
J'ai utilisé filtre() pour filtrer les dictionnaires avec des clés spécifiques.
Essayez le code en ligne à http://rextester.com/URYZW46252 (méthode moins efficace utilisant filtre() fonction).
Essayez aussi http://rextester.com/HLVQL50077 (en utilisant compréhension de la liste ce qui est un moyen efficace).
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; # {}