alwbtc
alwbtc

Reputation: 29495

Getting the key with max value in a portion of a python dictionary

I have a python dictionary, its keys are datetime.datetime objects, such as:

a = {datetime(2018,1,1):1, datetime(2018,1,2):2, datetime(2018,1,3):3, ...}

I would like to get the key (date) with max value in a portion of this dictionary, such as between dates 2018-03-27 and 2018-04-17.

What is the mosy pythonic way of achieving this?

Upvotes: 0

Views: 305

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78554

You can constrain the keys to that range of date using a generator expression and then take the one with the maximum value by passing the key as a.get:

date = max((k for k in a if datetime(2018, 03, 27) <= k <= datetime(2018, 04, 17)), 
            key=a.get)

Upvotes: 2

mhawke
mhawke

Reputation: 87134

First select those items in the dictionary having a key between the required values, then find the one with the largest value:

from datetime import datetime

min_date = datetime(2018, 3, 27)
max_date = datetime(2018, 4, 17)

date = max((d[k], k) for k in d if min_date <= k <= max_date)[1]

This code creates a sequence of tuples containing the value and datetime (N.B. in that order) between min_date and max_date. Then it chooses the item from that sequence with the largest value. The required data is the second element in the resulting tuple.

Upvotes: 3

Related Questions