Iterating across a filtered list
Drew
olsonas at gmail.com
Tue Mar 13 14:54:07 EDT 2007
On Mar 13, 2:42 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> If I can decipher your Ruby example (I don't know Ruby), I think you
> want:
>
> for name,contact in contacts.iteritems():
> if re.search('search', name):
> print contact
>
> If you just want to filter the dictionary inside an expression, you
> can use a generator expression:
>
> d = ((name,contact) for (name,contact) in contacts.iteritems() \
> if re.search('search', name))
>
> print '\n'.join(d) # prints items from filtered dict, one per line
>
> Note that d is an iterator, which means it mutates when you step
> through it.
Paul -
You're exactly on the mark. I guess I was just wondering if your first
example (that is, breaking the if statement away from the iteration)
was preferred rather than initially filtering and then iterating.
However, you're examples make a lot of sense are are quite helpful.
Thanks,
Drew
More information about the Python-list
mailing list