[BangPypers] list to dictionary problem

Nitin Kumar nitin.nitp at gmail.com
Tue Jun 22 10:54:14 CEST 2010


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 <orsenthil at gmail.com>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
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>



-- 
Nitin K


More information about the BangPypers mailing list