3

Inside my layer there are fields like this:

name | data | length
name_a | field_a_x | ...
name_b | field_b_x | ...
name_c | field_c_x | ...
name_d | field_d_x | ...

Is it possible to iterate only over the data-column, get the fields into a list and replace the data after calculating (or doing something else...)? The calculating-part will be easy but I'm having trouble understanding how to get and afterwards replace the data?

This is what I got so far...

from qgis.core import QgsProject
layer_name = "ExampleLayer"
layer = QgsProject.instance().mapLayersByName(layer_name)[0]
ftrs = layer.getFeatures()
list_old = []
for feat in layer.getFeatures():
 list_old.append(feat['data'])
Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked May 11, 2021 at 8:30
2
  • 3
    hello, can you add the result you are waiting for or an example of expression you would like to use ? Commented May 11, 2021 at 9:02
  • @CorentinLemaitre The new list could be anything actually! My problem is how to get the data into the field (updating) Commented May 11, 2021 at 11:17

1 Answer 1

4

One example:

lyr = iface.activeLayer()
feats = [f for f in lyr.getFeatures()] #List all features
#names = [f['KOMMUNNAMN'] for f in feats] #List values in KOMMUNNAMN field
#['Kiruna', 'Pajala', 'Gällivare', 'Jokkmokk', 'Boden']
fieldindex = lyr.fields().indexFromName('KOMMUNNAMN')
attrMap = {}
for f in feats:
 attrMap[f.id()] = {fieldindex:f['KOMMUNNAMN'].upper()}
#attrMap
#{0: {3: 'KIRUNA'}, 1: {3: 'PAJALA'}, 2: {3: 'GÄLLIVARE'}, 3: {3: 'JOKKMOKK'}, 4: {3: 'BODEN'}}
lyr.dataProvider().changeAttributeValues(attrMap)

enter image description here

answered May 11, 2021 at 16:43
1
  • 2
    Thank you very much for your help! Commented May 12, 2021 at 4:54

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.