[BangPypers] list to dictionary problem
Senthil Kumaran
orsenthil at gmail.com
Tue Jun 22 05:13:08 CEST 2010
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!
More information about the BangPypers
mailing list