better way to do this in python

Dan Stromberg drsalists at gmail.com
Sat Apr 2 22:59:17 EDT 2011


On Sat, Apr 2, 2011 at 5:24 PM, Chris Angelico <rosuav at gmail.com> wrote:

> On Sun, Apr 3, 2011 at 9:58 AM, Mag Gam <magawake at gmail.com> wrote:
> > 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?
>
> I think you want collections.Counter. From the docs: "Counter objects
> have a dictionary interface except that they return a zero count for
> missing items instead of raising a KeyError".
>
> ChrisA
>

I realize you (Mag) asked for a Python solution, but since you mention
awk... you can also do this with "sort < input | uniq -c" - one line of
"code".  GNU sort doesn't use as nice an algorithm as a hashing-based
solution (like you'd probably use with Python), but for a sort, GNU sort's
quite good.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110402/21ad3c76/attachment-0001.html>


More information about the Python-list mailing list