[Baypiggies] list to dictionary problem

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


More elegant, possible slower for long lists (the *zip(*a) bit):

>>> a = [['cat',2],['cat',5],['cat',9],['dog',6]]
>>> d = {}
>>> map(d.setdefault, *zip(*a))
[2, 2, 2, 6]
>>> d
{'dog': 6, 'cat': 2}

  - Jeremy

On Mon, Jun 21, 2010 at 8:04 PM, Jeremy Fishman
<jeremy.r.fishman at gmail.com>wrote:

> 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/838fab80/attachment.html>


More information about the Baypiggies mailing list