duck typing at will
MRAB
google at mrabarnett.plus.com
Tue Dec 30 14:04:11 EST 2008
Jose Mora wrote:
> Duck typing is called that way because "If it looks like a duck and
> quacks like a duck, it must be a duck." I think it would be good to
> have also "If the programmer wants to deal with it like a duck, it
> must be a duck"
>
> I mean, some tasks are rather boring in python when compared with php,
> for example, let's imagine we have a dictionary that contains
> dictionaries that contain the times that a key appears. We, or at
> least I, would like to write something as short as:
>
> dict[k1][k2] += 1
>
> However we will have to do a longer code (this is the smallest code I
> could come up with):
>
> dict = {}
> if not k1 in dict:
> dict[k1] = {}
> if not k2 in dict[k1]:
> dict[k1][k2] = 0
> dict[k1][k2] += 1
>
> I know it is not the Apocalypse nor something really important when
> compared with other things, but maybe it would be better if it wasn't
> necessary to declare the variables when they are built-in types or to
> initialize the keys in a dictionary, having special values (the
> identity element of the operation that causes the initialization) to
> initialize when it has not been done, initializing with the most
> general type that supports the operation that causes the
> initialization, casting to other type if necessary after that.
>
> This is just an idea, maybe I'm not the first one suggesting it, or
> maybe it is completely impossible to implement it because it would
> require deep changes in python, but I wanted to discuss it.
>
You could use defaultdict like this:
from collections import defaultdict
my_dict = defaultdict(lambda: defaultdict(int))
my_dict[k1][k2] += 1
The disadvantage is that my_dict will then return values even when you
don't want it to:
>>> print my_dict[unknown_key]
defaultdict(<type 'int'>, {})
so after you've filled it you might want to turn it into a 'normal' dict
of dict:
my_dict = dict((key, dict(inner.iteritems())) for key, inner in
my_dict.iteritems())
More information about the Python-list
mailing list