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,136
  • 29
  • 109
  • 338
Lorenzo
  • 1,085
  • 1
  • 6
  • 18

1 Answers1

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()
ThomasG77
  • 30,725
  • 1
  • 53
  • 93