× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Default Dictionaries

Mar 03, 2016
<p>It is common to want some kind of counter where you have some data values and you wish to keep a count of how many of each kind. So for example if you have a list of numbers </p> <p>numbers = [1, 3, 8, 2, 4, 3, 1, .....]</p> <p>you might wish to count how many there are of each number. A first attempt might look like this:</p> <p> </p> <p>d = dict()</p> <p>for x in numbers:</p> <p>    if x not in d:</p> <p>         d[x] = 0</p> <p>    else:</p> <p>         d[x] += 1</p> <p> </p> <p>However the standard library has a dictionary for exactly this, it's in the 'collections' module and is called 'defaultdict', you have to give it a function to create a default value, but that is easy for integers it is just 'int'. So the above can be re-written as simply:</p> <p> </p> <p>import collections</p> <p>d = collections.defaultdict(int)</p> <p>for x in l:</p> <p>   d[x] += 1</p> <p> </p> <p> </p>
comments powered by Disqus