Marshall
Marshall

Reputation: 137

MAX or latest Value from a list of dict in Python

I have a list of dictionary as below

[
    {'ClientId': 70433, 'ReportDate': '2020-05-01', 'JobId': 389512, 'AccountPnlCount': 507, 'DeskPnlCount': 545, 'ThresholdName': 'Threshold2', 'RuleName': 'PnlRowCountCheck', 'StartTime': datetime.datetime(2020, 5, 1, 21, 8, 32, 940000), 'CSTTimeStr': '2020-05-01T21:08:32.940000Z'},
    {'ClientId': 70433, 'ReportDate': '2020-05-01',  'JobId': 389525, 'AccountPnlCount': 507, 'DeskPnlCount': 545, 'ThresholdName': 'Threshold2', 'RuleName': 'PnlRowCountCheck', 'StartTime': datetime.datetime(2020, 5, 2, 0, 15, 21, 820000), 'CSTTimeStr': '2020-05-02T00:15:21.820000Z'}
]

I need the latest record JobId number Based on StartTime. i.e. for the MAX of "StartTime" I need the corresponding JobId, which is 389525.

Can you please assist? thank You

Upvotes: 0

Views: 83

Answers (1)

Samwise
Samwise

Reputation: 71424

Use max with a key argument to find the dictionary, then just get the JobId out of that dictionary:

>>> derp
[{'ClientId': 70433, 'ReportDate': '2020-05-01', 'JobId': 389512, 'AccountPnlCount': 507, 'DeskPnlCount': 545, 'ThresholdName': 'Threshold2', 'RuleName': 'PnlRowCountCheck', 'StartTime': datetime.datetime(2020, 5, 1, 21, 8, 32, 940000), 'CSTTimeStr': '2020-05-01T21:08:32.940000Z'}, {'ClientId': 70433, 'ReportDate': '2020-05-01', 'JobId': 389525, 'AccountPnlCount': 507, 'DeskPnlCount': 545, 'ThresholdName': 'Threshold2', 'RuleName': 'PnlRowCountCheck', 'StartTime': datetime.datetime(2020, 5, 2, 0, 15, 21, 820000), 'CSTTimeStr': '2020-05-02T00:15:21.820000Z'}]
>>> max(derp, key=lambda d: d['StartTime'])['JobId']
389525

Upvotes: 1

Related Questions