How can we generate a single dictionary for the output of the code below?

Consider the following code, which is a simple code:

import networkx as nx
import math

G = nx.read_gml(".../networks/karate.gml",label=None)

X = nx.single_source_shortest_path_length(G,5,2)
t = 0 
for x in X:
    if (34,x) in G.edges() or (x,34) in G.edges():
        t += 1
    l = dict()
    l[x] = t + math.log10(5)
    print(l)

An example of the output of this code is as follows:

{5: 1.6989700043360187}
{1: 1.6989700043360187}
{11: 2.6989700043360187}
{7: 3.6989700043360187}
{32: 4.698970004336019}
{2: 5.698970004336019}
{3: 6.698970004336019}
{4: 7.698970004336019}
{6: 8.698970004336019}

How can we put these outputs into a dictionary or two? It means to merge them together.

We expect an output like the following:

{5: 1.6989700043360187, 1: 1.6989700043360187, 11: 2.6989700043360187, 7: 3.6989700043360187, 32: 4.698970004336019, 2: 5.698970004336019, 3: 6.698970004336019, 4: 7.698970004336019 ,6: 8.698970004336019}

>Solution :

Move l = dict() outside and above the for, and unindent the print(l) line. Like this:

import networkx as nx
import math

G = nx.read_gml(".../networks/karate.gml",label=None)

X = nx.single_source_shortest_path_length(G,5,2)
t = 0 
l = dict()
for x in X:
    if (34,x) in G.edges() or (x,34) in G.edges():
        t += 1
    l[x] = t + math.log10(5)
print(l)

Explanation: the code inside the loop (i.e. below the for line, indented) runs many times, once for each iteration of the loop. Since you want to create a single dict, and you want to print it once (after the loop has finished), you have to move those lines outside the loop.

Please note that the shorter and more common form l = {} does the same as l = dict().

Leave a Reply