[BangPypers] Dictionary in Python - A doubt

Jins Thomas jinsthomas at gmail.com
Thu Mar 24 13:04:58 CET 2011


Hi all,

This is a very basic doubt. I was experimenting concept of dictionary in
python3

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.

Also i'm looking for some sites similar to perlmonks.org in python. There in
perlmonks we could see lots of small small articles (basic and advanced)
which will give clear idea on the usage, style etc. Have you heard of
anything of that sort.

Thanks
Jins Thomas


More information about the BangPypers mailing list