Odd-R. wrote:
> On 2005-07-22, John Machin <[EMAIL PROTECTED]> wrote:
> > Odd-R. wrote:
> >> I have this list:
> >>
> >> [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]
> >>
> >> All the dictionaries of this list are of the same form, and all the oids
> >> are distinct. If I have an oid and the list, how is the simplest way of
> >> getting the dictionary that holds this oid?
> >>
> >
> > Something like this:
> >
> > def oidfinder(an_oid, the_list):
> >      for d in the_list:
> >     if d['oid'] == an_oid:
> >              return d
> >      return None
> >      # These are not the oids you are looking for.
>
> Thank you for your help, but I was hoping for an even simpler
> solution, as I am suppose to use it in a
> <tal:block tal:define="p python: sentence.
>
> Is there a simpler way of doing it? What if I assume that the
> oid I'm searching for really exists?

If you really, really, really don't care about proper error handling,
both of these expressions should work: (warning, untested since I'm at
work)
right_oid = [d for d in dictlist if d['oid']==the_oid][0]
right_oid = (d for d in dictlist if d['oid']==the_oid).next()

The last one more efficient as a generator expression, but requires
Python2.4.  Both of these error in Really Bad Ways (range error and
StopIteration exceptions, respectively) if the right dictionary isn't
in the list.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to