better way to do this in python

Mag Gam magawake at gmail.com
Sun Apr 3 01:58:09 CEST 2011


I have a file like this,


cat file
aaa
bbb
aaa
aaa
aaa

awk '{x[$1]++}END { for (i in x) {print i,x[i]} } ' test
bbb 1
aaa 4


I suppose I can do something like this.
(pseudocode)

d={}
try:
 d[key]+=1
except KeyError:
 d[key]=1


I was wondering if there is a pythonic way of doing this? I plan on
doing this many times for various files. Would the python collections
class be sufficient?



More information about the Python-list mailing list