Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Filter dictionaries with specific keys (using list comprehension)
#python 2.7.12 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 = filter(lambda d: d["id"] == id, tasks) tasks = [d for d in tasks if d["id"] == id] # Pick the last dictionary and return it if tasks: return tasks[len(tasks) - 1] else: return {} 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; # {}
run
|
edit
|
history
|
help
0
Chain length calculator
Lambda
PyClassInit
Problem: binary
mad libs game
working with strings
PyDicCom
Lambda
Python learning
gvgvg