[Baypiggies] list to dictionary problem

Almir Karic almir at almirkaric.com
Tue Jun 22 04:56:18 CEST 2010


List comprehension is one option


>>> a = [['cat', 2], ['cat', 5], ['cat', 9], ['dog', 6]]
>>> [i[1] for i in a if i[0] == 'cat'][0]
2


On Mon, Jun 21, 2010 at 7:22 PM, 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
>
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies



--
python/django hacker & sys admin
http://almirkaric.com & http://twitter.com/redduck666


More information about the Baypiggies mailing list