[Baypiggies] list to dictionary problem

Zachary Collins recursive.cookie.jar at gmail.com
Tue Jun 22 12:11:27 CEST 2010


How about just using an iterator?

>>> a = [['cat',2],['cat',5],['cat',9],['dog',6]]
>>> (v for k, v in a if k == 'cat').next()
2

Also has the nice property of only iterating until the first item is found,
instead of iterating over the entire list like other solutions here.

On Tue, Jun 22, 2010 at 11:22 AM, Vikram <kpguy at rediffmail.com> 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.
>
> >>> 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).
>
> Thanks,
> Vikram
>
> <http://sigads.rediff.com/RealMedia/ads/click_nx.ads/www.rediffmail.com/signatureline.htm@Middle?>
> _______________________________________________
> 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/97731193/attachment.html>


More information about the Baypiggies mailing list