duck typing at will

Ned Deily nad at acm.org
Tue Dec 30 20:13:47 CET 2008


In article 
<6e1bfdea0812301042x70ab57capf99ce73d364d54db at mail.gmail.com>,
 "Jose Mora" <trylks at gmail.com> wrote:
>[...]
> 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

How about one line plus an import?

$ python2.5
Python 2.5.3c1 (release25-maint, Dec 17 2008, 21:50:37) 
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> dic = defaultdict(lambda : defaultdict(int))

>>> dic["spam"]["eggs"] += 1
>>> dic[42][3] += 1
>>> dic[42][3] += 1
>>> dic[42][3]
2
>>> dic
defaultdict(<function <lambda> at 0x661f0>, {42: defaultdict(<type 
'int'>, {3: 2}), 'spam': defaultdict(<type 'int'>, {'eggs': 1})})

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list