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>The check that element exists in <code>dict</code> is not really necessary. You can just use <code>collections.defaultdict</code>. Its initialization accepts callable object (like function) that will be called if you want to access (or assign something to) element that does not exist to generate the value (i.e. function that generates default value). For your case, it can be just <code>int</code>. I.e.</p>

<pre><code>import collections
local_path_length_hist = collections.defaultdict(int)
# you could say collections.defaultdict(lambda : 0) instead
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:
        local_path_length_hist[dist] += 1
</code></pre>

<p>You could turn the last two lines in one like that, but there is really no point.</p>

python performance list dictionary graph-tool