[BangPypers] Dictionary in Python - A doubt

Senthil Kumaran orsenthil at gmail.com
Thu Mar 24 13:10:33 CET 2011


On Thu, Mar 24, 2011 at 05:34:58PM +0530, Jins Thomas wrote:
> 
> I was just comparing hash in Perl. In Perl 'if i in count:  else:' statement
> is not required i could simply uses count{i} +=1 even if it exists or not
> exists. I was thinking why Python has put this restriction. Or is it
> something which i did wrongly.

That is not a restriction. That is consistent in understanding of how
dictionary is supposed to behave.

BTW for perl equivalent behavior, look at collections.defaultdict

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]


-- 
Senthil


More information about the BangPypers mailing list