[BangPypers] partial flattening of list

Anand Balachandran Pillai abpillai at gmail.com
Thu Jul 29 05:55:36 CEST 2010


On Wed, Jul 28, 2010 at 12:49 AM, Jeffrey Jose <jeffjosejeff at gmail.com>wrote:

> On Tue, Jul 27, 2010 at 4:15 PM, Vikram <kpguy at rediffmail.com> wrote:
>
> >
> > Hi Anand,vijay, and others,
> > we have python 2.4.3 at our workplace and defaultdict is not present in
> the
> > collections module in this python version.
> >
> > >>> dir(collections)
> > ['__doc__', '__file__', '__name__', 'deque']
> > >>>
> >
>
> I dont have python 2.4.3 right now to test what I'm going to say, but
> behaviour of defaultdict can be simulated (correct me if I'm wrong, again
> because of version freeze I'm never over 2.5.1) using dict.setdefault
>
>
> The way I understand defaultdict is, it never raise a KeyError, instead
> assumes the default 'value' of every key as the one that you initialize it
> with (here= list)
>
>
>
> d = {}
>
> and instead of doing
>
> d[key_doesnt_exist] = my_values
>
> do
>
> d.setdefault(key_doesnt_exist, []).extend(my_values)
>
>
Yes, this approach works if you haven't got collections.defaultdict.

>>> l=[['NM100', 1, 2], ['NM100', 3, 4], ['NM200', 5, 6]]
>>> d={}
>>> l2=[[x[0], x[1:]] for x in l]
>>> for k,v in l2: d.setdefault(k,[]).extend(v)
...
>>> d
{'NM100': [1, 2, 3, 4], 'NM200': [5, 6]}


> # if key doesnt exist, it returns the default (second argument) .. and you
> can call methods on it - append, extend .. what have you.
>
>
> I'm assuming you know this already and hence this rather vague description.
> If you want more pointers just ask I can reply in a much more descriptive
> way.
>
> HTH
> /jeff
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>



-- 
--Anand


More information about the BangPypers mailing list