I have 10 fields in my shapefile, and I want to use Python (3.7) to access the value of one field in QGIS.
When I run my code (below) I get a KeyError: '6' (index position of the field), implying that the field lookup worked, but that once I try to access the value, the field doesn't exist.
f = layer.getFeature(fid)
index = layer.fields().lookupField('length')
print("length: ", f[index])
I also tried:
f = layer.getFeature(fid)
index = layer.fields().indexFromName('length')
print("length: ", f[index])
Both throw the same error.
Sample code uses just in a print statement, but I need to use the index number at various points/for different methods.
Clarification: the field look up returns index 6, which is the correct index corresponding to the field length. It's only when I go to use that index number that I then get a Key Error stating that the field doesn't exist.
point_layer = iface.addVectorLayer("...file path.shp", "points", 'ogr')
main_layer = iface.activeLayer()
...more code making lists...
for v_id in list:
idx = point_layer.fields().lookupField('segment_id')
v = point_layer.getFeature(v_id)
segment_id = v[idx]
s = main_layer.getFeature(segment_id)
idx = layer.fields().lookupField('length')
print("length: ", s.attributes()[idx]) #throws IndexError: list index out of range
print("length: ", s[idx]) #throws KeyError
Image: Works through console - I know the field index is right and the value exists
index
and after isidx
f.attributes()[idx]
(qgis.org/api/… and gis.stackexchange.com/a/54059/2856)layer
andfid
?