[BangPypers] list to dictionary problem

Noufal Ibrahim noufal at gmail.com
Wed Jun 23 08:27:24 CEST 2010


On Tue, Jun 22, 2010 at 7:53 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).

I don't know about elegant/nice but the first thing that occured to me was
x = [['cat', 2], ['cat', 5], ['cat', 9], ['dog', 6]]

[t[1] for t in x if t[0] == 'cat'][-1] # Last value (no error checking)

(t[1] for t in x if t[0] == 'cat').next() # First value.

You can use a genexp for the latter since we can stop as soon as we
see one item. For the former, you'll have to go through the whole list
anyway.
I mtimed the former against the dict approach and got roughly the same
speed (there was some 0.01 sec. difference).

The first is a little wasteful though. You make an entire list and
then throw it away.

-- 
~noufal
http://nibrahim.net.in


More information about the BangPypers mailing list