My layer contains buildings. They have a number (num), a height and a height class (h) between 1 and 4.

The script aims to for each building list:

  1. the neighboring buildings (NEIGHBORS),
  2. the heights of these buildings (h_n)
  3. and the sum of the height classes of the neighboring buildings (SUM).

The script correctly retrieves the list of neighboring buildings (NEIGHBORS), the sum of building height classes (SUM) but does not return the height classes corresponding to each neighboring building (h_n).

Can someone tell me what is blocking?

# inspired script Mr. Ujaval Gandhi
from qgis.utils import iface
from PyQt5.QtCore import QVariant

_NAME_FIELD = 'num' # numero bt
_H_FIELD = 'h'      # hauteur bt
_SUM_FIELD = 'h'    # somme hauteurs bts voisins

_NEW_NEIGHBORS_FIELD = 'NEIGHBORS' # numero des bts voisins
_NEW_H_NEIGHBORS_FIELD = 'H_N' # hauteur des bts voisins
_NEW_SUM_FIELD = 'SUM_H' # somme hauteur des bts voisins

layer = iface.activeLayer()
        [QgsField(_NEW_NEIGHBORS_FIELD, QVariant.String),
        QgsField(_NEW_H_NEIGHBORS_FIELD, QVariant.Int),
        QgsField(_NEW_SUM_FIELD, QVariant.Int)])

feature_dict = {f.id(): f for f in layer.getFeatures()}

index = QgsSpatialIndex()
for f in feature_dict.values():
for f in feature_dict.values():
    print ('Working on %s' % f[_NAME_FIELD])
    geom = f.geometry()
    intersecting_ids = index.intersects(geom.boundingBox())
    neighbors = []
    h_n = []
    neighbors_sum = 0
    for intersecting_id in intersecting_ids:
        intersecting_f = feature_dict[intersecting_id]
        if (f != intersecting_f and
            not intersecting_f.geometry().disjoint(geom)):
            neighbors_sum += intersecting_f[_SUM_FIELD]
    f[_NEW_NEIGHBORS_FIELD] = ','.join(map(str, neighbors))
    f[_NEW_H_NEIGHBORS_FIELD] = ','.join(str(x) for x in h_n)
    f[_NEW_SUM_FIELD] = neighbors_sum
print ('Processing complete.')

enter image description here

  • What do you mean by blocking, do you get an error?
    – Bera
    Commented Feb 2, 2022 at 17:12
  • @BERA the script finishes without error but the variable h_n does not list the heights of neighboring buildings.
    – fcka
    Commented Feb 2, 2022 at 18:04

1 Answer 1



f[_NEW_H_NEIGHBORS_FIELD] = ','.join(str(x) for x in h_n)


f[_NEW_H_NEIGHBORS_FIELD] = ','.join(map(str, h_n))`

it works!

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.