5

I have a QGIS3 layer which has an attribute column indicating the id of each features. I want to add two more fields and fill them with some values ​​taken from a python list.

The list is something like that:

l = [['1', 'something', 'something else']]

where '1' is the id of the feature and 'something' and 'something else' are the values ​​that must fill the column in correspondence with the right id.

 data_provider = layer.dataProvider()
 data_provider.addAttributes([QgsField('field1', QVariant.String)])
 data_provider.addAttributes([QgsField('field2', QVariant.String)])
 layer.updateFields()
 l = [['1', 'something', 'something else'],['2', 'something', 'something else']]

I tried in this way:

mem_layer.startEditing()
for feat in mem_layer.getFeatures(): 
 for i in l:
 if str(feat["id"])==i[0]:
 feat.setFields(feat.fields(),True)
 feat.setAttribute('field1', i[1])
 feat.setAttribute('field2', i[2])
mem_layer.commitChanges()

But nothing changed. How to solve this?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Feb 6, 2020 at 18:13

1 Answer 1

4

A correction. Code mainly borrowed from Setting feature attribute by name via QGIS python api? answer

layer = iface.activeLayer() # I select the layer I want to modify, not needed for your case normally
data_provider = layer.dataProvider()
data_provider.addAttributes([QgsField('field1', QVariant.String)])
data_provider.addAttributes([QgsField('field2', QVariant.String)])
layer.updateFields()
l = [['1', 'something', 'something else'],['2', 'something', 'something else']]
layer.startEditing()
for feat in layer.getFeatures(): 
 for i in l:
 if str(feat["id"])==i[0]:
 feat['field1'] = i[1] # modification here
 feat['field2'] = i[2] # modification here
 layer.updateFeature(feat) # modification here
layer.commitChanges()
answered Feb 6, 2020 at 19:37
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.