I'm working with code from the Disconnected Islands plugin in QGIS x64 and Python 3. Normally, the plugin uses networkx to create a geometric network and ends by writing the FID of features with no connections to a CSV and their corresponding network group ID.

I'm not familiar with network theory/geometric networks, so I'm not sure if this is possible: is there a way to return the fid of segments with only one connection? If so, which part of the code should I change?

# get the network
layer = iface.activeLayer()
G = nx.Graph()

# construct graph
for feat in layer.getFeatures():
    line = feat.geometry().asPolyline()
    for i in range(len(line)-1):
        G.add_edges_from([((line[i][0], line[i][1]), (line[i+1][0], line[i+1][1]), 
                          {'fid': feat.id()})])

# evaluate on connected components
connected_components = list(nx.connected_component_subgraphs(G))

# gather edges and components to which they belong
fid_comp = {}
for i, graph in enumerate(connected_components):
   for edge in graph.edges_iter(data=True):
       fid_comp[edge[2].get('fid', None)] = i

1 Answer 1


If I'm not mistaken, this is very similar to your previous question.

Only now, instead of finding isolated features (1 feature in a network group), you want to find features with only one connection (2 features in a network group).

You should be able to adapt my answer from the previous question.

Having established that fid_comp is a dictionary containing feature id as key and component id as value, you want to find all the keys which each have exactly one duplicate value.

Assuming that a small example of the fid_comp dictionary might look something like this:

fid_comp = {1: 0, 2: 0, 3: 1, 4: 1, 5: 1, 6: 2, 7: 3, 8: 3, 9: 4, 10: 5, 11: 6, 12: 6}

Try this:

countMap = {}
for v in fid_comp.values():
    countMap[v] = countMap.get(v,0) + 1
pairs = [k for k, v in fid_comp.items() if countMap[v] == 2]
#select features if desired
  • Thanks so much! I understand the code/theory itself much better now :)
    – jyingling
    Commented Jan 31, 2019 at 17:36
  • You're welcome, glad it helped.
    – Ben W
    Commented Feb 1, 2019 at 2:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.