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>I think you can bypass this code entirely. Your question is tagged with <a href="/questions/tagged/graph-tool" class="post-tag" title="show questions tagged &#39;graph-tool&#39;" rel="tag">graph-tool</a>. Take a look at this section of their documentation: <a href="https://graph-tool.skewed.de/static/doc/stats.html?highlight=degree%20histogram#graph_tool.stats.vertex_hist" rel="nofollow">graph_tool.stats.vertex_hist</a>. </p>

<p>Excerpt from linked documentation:</p>

<blockquote>
  <p><strong>graph_tool.stats.vertex_hist(g, deg, bins=[0, 1], float_count=True)</strong><br>
  Return the vertex histogram of the given degree type or property.</p>
  
  <p><em>Parameters:</em><br>
  g : Graph
  &emsp;Graph to be used.<br>
  deg : string or PropertyMap<br>
  &emsp;Degree or property to be used for the histogram. It can be either âinâ, âoutâ or âtotalâ, for in-,<br>
  &emsp;out-, or total degree of the vertices. It can also be a vertex property map.<br>
  bins : list of bins (optional, default: [0, 1])<br>
  &emsp;List of bins to be used for the histogram. The values given represent the edges of the bins<br>
  &emsp;(i.e. lower and upper bounds). If the list contains two values, this will be used to automatically<br>
  &emsp;create an appropriate bin range, with a constant width given by the second value, and starting<br>
  &emsp;from the first value.<br>
  float_count : bool (optional, default: True)<br>
  &emsp;If True, the counts in each histogram bin will be returned as floats. If False, they will be<br>
  &emsp;returned as integers.  </p>
  
  <p><em>Returns:</em> 
  counts : ndarray<br>
  &emsp;The bin counts.<br>
  bins : ndarray<br>
  &emsp;The bin edges.  </p>
</blockquote>

<p>This will return the edges grouped like a histogram in an <code>ndarray</code>. You can then just get the length of the <code>ndarray</code> columns to get your counts to generate the histogram.</p>

python performance list dictionary graph-tool