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

enter image description here


The solution is simpler:

print("length: ", f['length'])
  • The goal of my code is not actually to print the value, I need to use other methods that require an index value and are also throwing the key error. – jyingling Feb 15 at 19:21
  • @jyingling please update the question to reflect this requirement – underdark Feb 15 at 19:23

Use this

print("length: ", f.attributes()[index])

or loop all features

layer = iface.activeLayer()             
index = layer.fields().indexFromName('length')
for f in layer.getFeatures():
    print (f.attributes()[index])
  • Threw IndexError: list index out of range – jyingling Feb 16 at 0:21
  • @jyingling, so the value of your fid variable do not correspond with any featureID of the layer? – Gabriel De Luca Feb 16 at 5:25
  • Clarified @GabrielDeLuca – jyingling Feb 18 at 14:14

Figured it out: my segment IDs weren't matching the actual feature IDs, so it was returning a key error because the previous code wasn't returning a feature.

for v_id in no_dup:
    v = point_layer.getFeature(v_id)

    seg_id = v[seg_idx]
    s_list = list(main_layer.getFeatures("seg_id = {}".format(seg_id)))
    s = s_list[0]

    len_idx = main_layer.fields().lookupField('length') 
    print("length: ", s[len_idx])

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.