2

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

jyingling
  • 477
  • 4
  • 21

3 Answers3

2

The solution is simpler:

print("length: ", f['length'])
underdark
  • 84,148
  • 21
  • 231
  • 413
  • 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 '19 at 19:21
  • @jyingling please update the question to reflect this requirement – underdark Feb 15 '19 at 19:23
2

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])
Fran Raga
  • 7,838
  • 3
  • 26
  • 47
0

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])
jyingling
  • 477
  • 4
  • 21