@@ -1906,9 +1906,6 @@ def from_networkx(cls, g):
19061906
19071907 @param g: networkx Graph or DiGraph
19081908 """
1909- import networkx as nx
1910- from collections import defaultdict
1911-
19121909 # Graph attributes
19131910 gattr = dict (g .graph )
19141911
@@ -1931,7 +1928,7 @@ def from_networkx(cls, g):
19311928
19321929 # Edges and edge attributes
19331930 eattr_names = {name for (_ , _ , data ) in g .edges .data () for name in data }
1934- eattr = defaultdict ( list )
1931+ eattr = { name : [] for name in eattr_names }
19351932 edges = []
19361933 for (u , v , data ) in g .edges .data ():
19371934 edges .append ((vd [u ], vd [v ]))
@@ -2029,13 +2026,19 @@ def from_graph_tool(cls, g):
20292026 for i in range (vcount ):
20302027 graph .vs [i ][key ] = prop [i ]
20312028
2032- # Edges
2033- # NOTE: the order the edges are put in is necessary to set the
2034- # attributes later on
2029+ # Edges and edge attributes
2030+ # NOTE: graph-tool is quite strongly typed, so each property is always
2031+ # defined for all edges, using default values for the type. E.g. for a
2032+ # string property/attribute the missing edges get an empty string.
2033+ edges = []
2034+ eattr_names = list (g .edge_properties )
2035+ eattr = {name : [] for name in eattr_names }
20352036 for e in g .edges ():
2036- edge = graph .add_edge (int (e .source ()), int (e .target ()))
2037- for key , val in list (g .edge_properties .items ()):
2038- edge [key ] = val [e ]
2037+ edges .append ((int (e .source ()), int (e .target ())))
2038+ for name , attr_map in list (g .edge_properties .items ()):
2039+ eattr [name ].append (attr_map [e ])
2040+
2041+ graph .add_edges (edges , eattr )
20392042
20402043 return graph
20412044
0 commit comments