Iterating across a filtered list

Paul Rubin http
Tue Mar 13 19:42:52 CET 2007


"Drew" <olsonas at gmail.com> writes:
> I'm currently writing a toy program as I learn python that acts as a
> simple address book. I've run across a situation in my search function
> where I want to iterate across a filtered list. My code is working
> just fine, but I'm wondering if this is the most "elegant" way to do
> this. Essentially, I'm searching the dict self.contacts for a key that
> matches the pattern entered by the user. If so, I print the value
> associated with that key. A pastie to the method is below, any help/
> advice is appreciated:

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.



More information about the Python-list mailing list