Unfortunately, the two layers don't cover the same size of area and therefore don't have the same number of attributes. That's the reason I only saw the following attempt, instead of simply zip them. So until now I tried to find attribute value matches between two layers by running a for loop through one layer within a for loop through the other one, to be able to check with an if statement, if the two layers attribute values are identical or not... It's not working correctly! And also not efficient enough, since I have to check all streets of an entire city (do I have something wrong? But I don't get an error message...?)

Or is there a more elegant way I don't know yet to complete and speed up this task?

here my code so far:

def addFeatures():
    polylines = QgsMapLayerRegistry.instance().mapLayersByName('polylines')[0]
    itlayer = QgsMapLayerRegistry.instance().mapLayersByName('itpoint')[0]
    tomaxspeed = itlayer.fieldNameIndex('tempo')
    tolanes = itlayer.fieldNameIndex('lanes')
    fspeed = polylines.fieldNameIndex('maxspeed')
    flanes = polylines.fieldNameIndex('lanes')
    for feat in itlayer.getFeatures():
        for ft in polylines.getFeatures():
            frommaxspeed = ft.attribute('maxspeed')
            fromlanes = ft.attribute('lanes')
            if ft.attribute('name') == feat.attribute('name'):
                if frommaxspeed:
                #print (maxspeed)
                    itlayer.changeAttributeValue(feat.id(), tomaxspeed, frommaxspeed)
                if fromlanes:
                    itlayer.changeAttributeValue(feat.id(), tolanes, fromlanes)

fixed line 18 and it works now as it should (stupid failure). But still, the perfomance is terrible and QGIS is not reacting for about 15 min while executing this function.

Doesn't seem to me, that it should be like this!?

Therefore, does PyQGIS offer a different and more efficient way?

  • I've added my comment as an answer – firefly-orange Aug 24 '17 at 14:36

Line 18 looks like it should be:

itlayer.changeAttributeValue(feat.id(), tolanes, fromlanes)?

You can also add the break command after itlayer.changeAttributeValue is called. This will stop the script continuing to loop through the features once a match has been found.

  • I already edited line 18 in the code above... ;-) and unfortunately I can't use break, because there are many matches (ideal would be one match for each street). – Nico Aug 24 '17 at 20:26
  • I have used a similar code but at this line: if ft.attribute('name_of field') == feat.attribute('name_of_field'): ..........it throws a key error where in the field exists. – rao Mar 7 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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