TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Counting elements with dictionary

2 pointsby kracekumarabout 11 years ago

1 comment

dalkeabout 11 years ago
That was the Pythonic approach until 2006. With Python 2.5 the Pythonic solution was often to use defaultdict:<p><pre><code> &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; words = [&#x27;a&#x27;, &#x27;the&#x27;, &#x27;an&#x27;, &#x27;a&#x27;, &#x27;an&#x27;, &#x27;the&#x27;] &gt;&gt;&gt; d = defaultdict(int) &gt;&gt;&gt; for word in words: ... d[word] += 1 ... &gt;&gt;&gt; d defaultdict(&lt;type &#x27;int&#x27;&gt;, {&#x27;a&#x27;: 2, &#x27;the&#x27;: 2, &#x27;an&#x27;: 2}) </code></pre> It&#x27;s a bit more cumbersome, but the performance is better, and defaultdict(list)[key].append() is much better than setdefault(key, []).append(value).<p>In modern Python (starting with Python 2.7, released in 2010), the Pythonic solution is collections.Counter:<p><pre><code> &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; words = [&#x27;a&#x27;, &#x27;the&#x27;, &#x27;an&#x27;, &#x27;a&#x27;, &#x27;an&#x27;, &#x27;the&#x27;] &gt;&gt;&gt; Counter(words) Counter({&#x27;a&#x27;: 2, &#x27;the&#x27;: 2, &#x27;an&#x27;: 2}) </code></pre> or dict(Counter(words)) if you want the result to return an actual dict instead of a Counter instance.