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 }
def get_records(dict_history, str_from_date, str_to_date):
for k,v in sorted(dict_history.items()):
if k>str_to_date:
break
if k>=str_from_date:
yield (k,v)
print history.items()
print
print list( get_records(history, '2005-05-21', '2008-12-25'))
Даты являются строками 'гггг-мм-дж'
Сортировка лексикографически этих строк приводит к тому же результату, что и сортировка по датам, которые они представляют.
sorted (dict_history.items ()) - список кортежей. Python сортирует этот список по первым элементам кортежей.
Каждый ключ в словаре уникален, в этой сортировке нет двусмысленности.
Редактировать 1
Отвечая на вашу проблему производительности:
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-11": 02,
"2008-11-10": 98,
"2008-11-19": 94,
"2008-11-18": 94,
"2004-05-27": 82,
"2004-05-26": 45,
"2004-05-25": 70 }
import bisect
def get_records(dict_history, str_from_date, str_to_date):
sorted_keys = sorted(dict_history.iterkeys())
start = bisect.bisect_left(sorted_keys,str_from_date)
end = bisect.bisect_right(sorted_keys,str_to_date)
for date in sorted(dict_history.iteritems())[start:end]:
yield date
print history.items()
print
print list( get_records(history, '2005-05-21', '2008-12-25'))