[BangPypers] partial flattening of list
Jeffrey Jose
jeffjosejeff at gmail.com
Tue Jul 27 21:19:41 CEST 2010
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)
# 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
More information about the BangPypers
mailing list