[Baypiggies] list to dictionary problem

Jeremy Fishman jeremy.r.fishman at gmail.com
Tue Jun 22 05:04:29 CEST 2010


Is a always ordered (as it is in the example)?

>>> from bisect import bisect_left
>>> a = [['cat',2],['cat',5],['cat',9],['dog',6]]
>>> i = bisect_left(a, ['cat'])
>>> if i < len(a):
...     print a[i]
...
['cat', 2]

Do you absolutely want a dictionary as a result?

>>> d = {}
>>> [d.setdefault(*pair) for pair in a]
[2, 2, 2, 6]
>>> d
{'dog': 6, 'cat': 2}

  - Jeremy

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
>
> <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/20100621/3ffb6108/attachment.html>


More information about the Baypiggies mailing list