Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a range of dates in Python dictionary

I have the following dictionary:

history = {
"2008-11-17": 41, 
"2010-05-28": 82, 
"2008-11-14": 47, 
"2008-11-13": 60, 
"2008-11-12": 56, 
"2008-11-11": 55, 
"2008-11-10": 98, 
"2008-11-19": 94, 
"2008-11-18": 94, 
"2004-05-27": 82, 
"2004-05-26": 45, 
"2004-05-25": 70,
# there's more ...
}

How do I define a generator function get_records(dict_history, str_from_date, str_to_date) to yield date: record entries?

I know how to convert datetime objects to any string format I want. However, my major pain points in this hurdle are:

  1. dicts aren't ordered.
  2. dict keys are strings.
  3. The dates are not continuous.

So far, this is what I can think of:

from datetime import datetime, timedelta

def get_records(history, start_date, end_date):
  fmt = "%Y-%m-%d"
  dt = timedelta(days=1)

  present_date = datetime.strptime(start_date, fmt)
  end_date = datetime.strptime(end_date, fmt)

  while present_date <= end_date:
    present_string = present_date.strftime(fmt)
    try:
      yield (present_string, history[present_string])
    except KeyError:
      pass
    present_date += dt

Is there a more efficient way to do that?

UPDATE (2011 Aug 2)
I found a SortedCollection class at ActiveState, also by Raymond Hettinger.

like image 467
Kit Avatar asked Oct 17 '25 16:10

Kit


1 Answers

I'd just iterate over the dictionary and return the items that match:

def get_records(history, start_date, end_date):
    for date, entry in history.iteritems():
        if start_date <= date <= end_date:
             yield date, entry

Note that your particular date format allows direct string comparison with < and > without converting to a datetime instance first.

Also note that the given function will return the matching items in no particular order.

like image 200
Sven Marnach Avatar answered Oct 20 '25 06:10

Sven Marnach