Can I search a list for a range of values?

Ian Kelly ian.g.kelly at gmail.com
Fri Oct 14 19:46:28 EDT 2011


On Fri, Oct 14, 2011 at 5:36 PM, Troy S <tdsimpson at gmail.com> wrote:
> Can something like this be done with dictionarys?
>
> For example, these are the keys in the dictionary from the call: dict.keys()
>
> ['20110601', '20110604', '20110608', '20110611', '20110615',
> '20110618', '20110622', '20110625', '20110629', '20110702',
> '20110706','20110709', '20110713', '20110716', '20110720', '20110723',
> '20110727', '20110730', '20110803', '20110806', '20110810','20110813',
> '20110817', '20110820', '20110824', '20110827', '20110831',
> '20110903', '20110907', '20110910', '20110914','20110917', '20110921',
> '20110924', '20110928', '20111001', '20111005', '20111008']
>
> Is there a way to find all items between '20110809' and '20110911'?
> So the subset would be:
> ['20110810','20110813', '20110817', '20110820', '20110824',
> '20110827', '20110831', '20110903', '20110907', '20110910']

Sure, dictionaries also support iteration.

date_range = [d for d in source_dict if '20110809' <= d <= '20110911']

Or if you want the result to also be a dictionary:

(Python 3)
date_range = {d:v for d, v in source_dict.items() if '20110809' <= d
<= '20110911'}

(Python 2)
date_range = dict((d,v) for d, v in source_dict.iteritems() if
'20110809' <= d <= '20110911')

You might also want to consider storing your dates as datetime.date
objects rather than strings, but since you already have them formatted
for lexicographical sorting it's not important for this.

Cheers,
Ian



More information about the Python-list mailing list