[BangPypers] Dictionary in Python - A doubt

Baishampayan Ghose b.ghose at gmail.com
Thu Mar 24 13:16:20 CET 2011

On Thu, Mar 24, 2011 at 5:34 PM, Jins Thomas <jinsthomas at gmail.com> wrote:
> My problem was to find the occurance of each word in a file
> f = open('hello.txt', 'r')
> count = {}
> for line in f:
>    words = line.split()
>    for i in words :
>        if i in count:
>            count[i] += 1
>        else:
>            count[i] = 1
> print (count)
> 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.

Perl let's you do a += on a dictionary value because Perl is weakly
typed(?) and Python is not. To tell Python to assume that the default
value of your dictionary is an integer instead of anything else, you
will have to use `defaultdict`[1] which is a subclass of the built-in
Python dict. This is how you can use it -

count = defaultdict(int)

with open("hello.txt", "r") as f:
    for line in f:
        words = line.split()
        for i in words:
            count[i] += 1

print (count)

Hope this helps.


[1] http://docs.python.org/library/collections.html#collections.defaultdict

Baishampayan Ghose
b.ghose at gmail.com

More information about the BangPypers mailing list