2 methods spring to my mind, first one is what Nitin Kumar has already
mentioned. Looping over a list of tuples. Make sure you have a sorted list
first.

a.sort()
for key, value in a:
  if key == "cat":
   break

# now value is 2

The second method is a little fancy, mentioning it here for the sake of
completeness.


# Note, I havent tested this code, but it should work.

import itertools

a.sort() # this is necessary, and anyway for a tuple sort() sorts it by
first element
groups = itertools.groupby(a, key = lambda x: x[0])

# now groups would look something like this
# [("cat", <sub-iterator>), ("dog", <sub-iterator>)]

# now loop through "groups", and when you hit "cat", extract the first item
out of <sub-iterator>

for key, iterator in groups:
  if key == "cat":
     break

firstValue = list(iterator)[0]
now iterator will yield values of "cat", starting with 2, 5, 9, 6



On Tue, Jun 22, 2010 at 2:24 PM, Nitin Kumar <[email protected]> wrote:

> for such things, always try to prefer tuple
>
> ex:
>
> >>> cache= (('cat',2),('cat',5),('cat',9),('dog',6))
> >>> for x,y in cache:
> print (x,y)
>
> cat 2
> cat 5
> cat 9
> dog 6
>
> On Tue, Jun 22, 2010 at 8:43 AM, Senthil Kumaran <[email protected]
> >wrote:
>
> > On Tue, Jun 22, 2010 at 02:23:43AM -0000, Vikram  wrote:
> > > Suppose i have this list:
> > >
> > > >>> a = [['cat',2],['cat',5],['cat',9],['dog',6]]
> > > >>> a
> > > [['cat', 2], ['cat', 5], ['cat', 9], ['dog', 6]]
> > >
> > > Now, there is a nice way to obtain the value 9.
> >
> > This is using the side effect of dict creation. Not a nice way. :)
> > The rule is that last value with the same key will be over-written. If
> > you use it any of your larger applications, the next person who is
> > going to read your code will likely be frustrated.
> >
> > > >>> z = dict(a)
> > > >>> z
> > > {'dog': 6, 'cat': 9}
> > >
> > > Is there any elegant way to extract the value 2? (Value corresponding
> to
> > the first occurence of 'cat' in the 2-D list
> >
> > Nope, it is not elegant.
> > The best way is to be explicit. Loop over list, create a dict with the
> > value as the list of values the original list and then deal with the
> > list value as you would like to. First element is "elegantly" [0] and
> > the last element is "nicely" [-1]. :)
> >
> > --
> > Senthil
> >
> > We don't understand the software, and sometimes we don't understand the
> > hardware, but we can *___   see* the blinking lights!
> > _______________________________________________
> > BangPypers mailing list
> > [email protected]
> > http://mail.python.org/mailman/listinfo/bangpypers
> >
>
>
>
> --
> Nitin K
> _______________________________________________
> BangPypers mailing list
> [email protected]
> http://mail.python.org/mailman/listinfo/bangpypers
>
_______________________________________________
BangPypers mailing list
[email protected]
http://mail.python.org/mailman/listinfo/bangpypers

Reply via email to