<br><div class="gmail_quote">On Sat, Apr 2, 2011 at 5:24 PM, Chris Angelico <span dir="ltr"><<a href="mailto:rosuav@gmail.com">rosuav@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
<div class="im">On Sun, Apr 3, 2011 at 9:58 AM, Mag Gam <<a href="mailto:magawake@gmail.com">magawake@gmail.com</a>> wrote:<br>
> I suppose I can do something like this.<br>
> (pseudocode)<br>
><br>
> d={}<br>
> try:<br>
>  d[key]+=1<br>
> except KeyError:<br>
>  d[key]=1<br>
><br>
><br>
> I was wondering if there is a pythonic way of doing this? I plan on<br>
> doing this many times for various files. Would the python collections<br>
> class be sufficient?<br>
<br>
</div>I think you want collections.Counter. From the docs: "Counter objects<br>
have a dictionary interface except that they return a zero count for<br>
missing items instead of raising a KeyError".<br>
<br>
ChrisA<br></blockquote><div><br>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.<br>
<br><br></div></div>