mercredi 15 juin 2016

Max-valued-elements from list group by element's code

I want to extract all elements of the maximum running date grouped by their codes from a list of dictionary. Here is what I got so far:

import datetime
from itertools import groupby

commission_list = [
    {'code': 'COMMISSION_CODE1', 'runningdt': datetime.datetime.strptime('2016-04-12', '%Y-%m-%d'), 'value': 150},
    {'code': 'COMMISSION_CODE1', 'runningdt': datetime.datetime.strptime('2016-04-12', '%Y-%m-%d'), 'value': 450},
    {'code': 'COMMISSION_CODE1', 'runningdt': datetime.datetime.strptime('2016-04-16', '%Y-%m-%d'), 'value': 140},
    {'code': 'COMMISSION_CODE1', 'runningdt': datetime.datetime.strptime('2016-04-17', '%Y-%m-%d'), 'value': 120},
    {'code': 'COMMISSION_CODE1', 'runningdt': datetime.datetime.strptime('2016-04-17', '%Y-%m-%d'), 'value': 220},

    {'code': 'COMMISSION_CODE2', 'runningdt': datetime.datetime.strptime('2016-04-11', '%Y-%m-%d'), 'value': 150},
    {'code': 'COMMISSION_CODE2', 'runningdt': datetime.datetime.strptime('2016-04-15', '%Y-%m-%d'), 'value': 140},
    {'code': 'COMMISSION_CODE2', 'runningdt': datetime.datetime.strptime('2016-04-16', '%Y-%m-%d'), 'value': 160},
    {'code': 'COMMISSION_CODE2', 'runningdt': datetime.datetime.strptime('2016-04-19', '%Y-%m-%d'), 'value': 210},

    {'code': 'COMMISSION_CODE3', 'runningdt': datetime.datetime.strptime('2016-04-16', '%Y-%m-%d'), 'value': 330},
    {'code': 'COMMISSION_CODE3', 'runningdt': datetime.datetime.strptime('2016-04-20', '%Y-%m-%d'), 'value': 310},
    {'code': 'COMMISSION_CODE3', 'runningdt': datetime.datetime.strptime('2016-04-20', '%Y-%m-%d'), 'value': 410},
]

latest_run_commissions = []
for key, commission_group in groupby(commission_list, lambda x: x['code']):
    tem = list(commission_group)
    the_last_com = (max(tem, key=lambda x: x['runningdt']))
    filtered_objs = filter(lambda f: f['runningdt'] == the_last_com['runningdt'], tem)
    for o in filtered_objs:
        latest_run_commissions.append(o)

for f in latest_run_commissions:
    print(f)
print(" ")

Are there any more effective and efficient ways out there? Your advice or suggestions will be much appreciated and welcomed.

Aucun commentaire:

Enregistrer un commentaire