sorting - How to sort a list of dictionaries in python? -


input data:

results= [         {       "timestamp_datetime": "2014-03-31 18:10:00 utc",       "job_id": 5,       "processor_utilization_percentage": 72     },         {       "timestamp_datetime": "2014-03-31 18:20:00 utc",       "job_id": 2,       "processor_utilization_percentage": 60     },         {       "timestamp_datetime": "2014-03-30 18:20:00 utc",       "job_id": 2,       "processor_utilization_percentage": 0     }] 

output has sorted below, grouping job_id in ascending order:

newresult = {     '2':[{ "timestamp_datetime": "2014-03-31 18:20:00 utc",             "processor_utilization_percentage": 60},            {"timestamp_datetime": "2014-03-30 18:20:00 utc",           "processor_utilization_percentage": 0},]      '5':[{           "timestamp_datetime": "2014-03-31 18:10:00 utc",           "processor_utilization_percentage": 72},         ],     } 

what pythonic way this?

you grouping; easiest collections.defaultdict() object:

from collections import defaultdict  newresult = defaultdict(list)  entry in result:     job_id = entry.pop('job_id')     newresult[job_id].append(entry) 

newresult dictionary , these not ordered; if need access job ids in ascending order, sort keys list them:

for job_id in sorted(newresult):     # loops on job ids in ascending order.     job in newresult[job_id]:         # entries per job id 

Comments

Popular posts from this blog

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -