Iteratively count elements in list and store count in dictionary
<p>I have a piece of code that loops through a set of nodes and counts the path length connecting the given node to each other node in my network. For each node my code returns me a list, <code>b</code> containing integer values giving me the path length for every possible connection. I want to count the number of occurences of given path lengths so I can create a histogram.</p>

<pre><code>local_path_length_hist = {}
for ver in vertices:
    dist = gt.shortest_distance(g, source=g.vertex(ver))
    a = dist.a
    #Delete some erroneous entries
    b = a[a!=2147483647]
    for dist in b:
        if dist in local_path_length_hist:
            local_path_length_hist[dist]+=1
        else:
            local_path_length_hist[dist]=1
</code></pre>

<p>This presumably is very crude coding as far as the dictionary update is concerned. Is there a better way of doing this? What is the most efficient way of creating this histogram?</p>

<p>There is a utility in the <code>collections</code> module called <code>Counter</code>. This is even cleaner than using a <code>defaultdict(int)</code></p>

<pre><code>from collections import Counter
hist = Counter()
for ver in vertices:
    dist = gt.shortest_distance(g, source=g.vertex(ver))
    a = dist.a
    #Delete some erroneous entries
    b = a[a!=2147483647]
    hist.update(b)
</code></pre>

python performance list dictionary graph-tool