3

I want to update an existing field according to another, it means the equivalent of a CASE WHEN .... THEN ..... ELSE .... END in SQL , but I want to know how to write this same update in Python for QGIS:

I wrote the following code:


#TEST : mettre à jour un champ existant avec boucle
from PyQt4.QtCore import *
from qgis.core import *
vl = iface.activeLayer()
vl.startEditing()

#step 1
vl.updateFields()
idx = vl.dataProvider().fieldNameIndex( 'ETIQUETTE' )
adduc = vl.dataProvider().fieldNameIndex( 'MODE_ADDUC' )

#step 2
for f in vl.getFeatures():
    if f[adduc] == 'AERIEN':
        f[idx] = 'CIEL'
    elif f[adduc] == 'FACADE':
        f[idx] = 'MUR'
    elif f[adduc] == 'SOUTERRAIN':
        f[idx] = 'TERRE'
    else:
        f[idx] = 'RIEN'
    vl.updateFeature( f ) 

vl.commitChanges()

but but I got a Python error :

Traceback (most recent call last):
  File "<input>", line 2, in <module>
KeyError: '-1'

Can you help me, please ?

  • 4
    Welcome to GIS.SE! Have you tried f['ETIQUETTE'] or f.attribute(idx)? Not sure whether the form f[...] acccepts integers or not. And is 'ETIQUETTE' the true attribute name? KeyError: '-1' looks like the attribute name is not existing to me. – Jochen Schwarze Feb 25 at 16:08
  • 1
    As a first troubleshooting step, print f to determine what kind of data you're getting back. Also print adduc. Note that indexes in Python start at 0. – smiller Feb 25 at 16:38
4

I think Jochen Schwarze is onto the problem. The fields need to be in quotes like this:

layer = iface.activeLayer()
print(layer)
all_features = layer.getFeatures()
layer.startEditing()
for feature in all_features:
    if feature['NUMBER'] == '1337':
        att = feature.attributes()
        print(att)
    else:
        print(feature['CODE'])
    if feature['NUMBER'] == '1345':
        print(feature['NUMBER'])
        feature.setAttributes(att)
        layer.updateFeature(feature)
        att = feature.attributes()
        print(att)

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.