[Baypiggies] list to dictionary problem

Andrew Akira Toulouse andrew at atoulou.se
Tue Jun 22 19:22:54 CEST 2010


More succinctly:
>>> a = [['cat',2],['cat',5],['cat',9],['dog',6]]
>>> dict(reversed(a))['cat']
2

IIRC, reversed() creates an iterator that iterates backwards. I'm not too
sure about the lower-level nuts and bolts of Python regarding this - maybe
someone else can shed some light on the advantages of iterators.

(there is also a sorted() function that creates similarly creates a sorted
iterator)

Zachary's solution does seem to be the laziest (as in least evaluated),
though - that's probably as good as you're going to get.

--Andy

On Tue, Jun 22, 2010 at 2:57 AM, Alexandre Conrad <
alexandre.conrad at gmail.com> wrote:

> Hello Vikram,
>
> 2010/6/22 Vikram <kpguy at rediffmail.com>
> >
> > 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.
> >
> > >>> 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).
>
> I guess I'd just reverse the list and apply the same technique as you
> proposed.
>
> >>> a = [['cat',2],['cat',5],['cat',9],['dog',6]]
> >>> a.reverse()
> >>> z = dict(a)
> >>> z
> {'dog': 6, 'cat': 2}
>
> Would that be suitable for you?
>
> Regards,
> --
> Alex
> twitter.com/alexconrad
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20100622/5ebc53b2/attachment-0001.html>


More information about the Baypiggies mailing list