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:
dict
s aren't ordered.dict
keys are strings.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With