To be more specific: I have a feature class for which some features have an entry for a variable ('KnownBj') and some not (have a 9999 entry). I want for each feature to find the 5 nearest neighbors that have an entry in 'KnownBj'. What I currently do is to prepare two dictionaries - A has all the features and B only the features with a 'KnownBj' .I add B to a SpatialIndex, and loop through A searching for neighbours with .NearestNeighbor:
canvas = qgis.utils.iface.mapCanvas()
layer = canvas.currentLayer()
iter = layer.selectedFeatures()
feature_dict = {f.id(): f for f in iter}
featDictKnownBj = {k: v for k, v in feature_dict.iteritems() if v[KnownBj] != '9999' }
#Prepare Spatial Index
SpatIndex = QgsSpatialIndex()
map(SpatIndex.insertFeature, featDictKnownBj.values())
#SEARCH NEIGHBOURS
NNDict = {}
for f in feature_dict.values():
NNs = SpatIndex.nearestNeighbor(f.geometry().centroid().asPoint(),5)
Now this seems to work, my question is - am I missing sth? Should I add the current feature to the Spatial Index, then search, then remove it and so for all, or should this be perfectly ok?