I have vector data: enter image description here

And would like to iterate over the attribute table returning only two field values. Isn't there a way to limit the values returned by getFeatures so all attributes does not have to be read? This work but seems convoluted:

layer = iface.activeLayer()
fields_to_return = ['KKOD','KATEGORI']
for feat in layer.getFeatures():
    print([feat[f] for f in fields_to_return])

[414, 'Kommun']
[414, 'Kommun']
[414, 'Kommun']

In ArcGIS I would do:

with arcpy.da_SearchCursor(r'C:\data.gdb\ak_riks',fields_to_return) as cursor:
    for row in cursor:

You should "very often" use QgsFeatureRequest :

If you need only a subset of attributes, and also maybe you don't need the geometry, you can do something like:

expected_fields = ['KKOD', 'KATEGORI']
layer = iface.activeLayer()
indexes = [layer.fields().indexFromName(field) for field in expected_fields]

request = QgsFeatureRequest()
for feature in layer.getFeatures(request):
    print(feature['KKOD'], feature['KATEGORI'])

You need to check your attributes index.

I really suggest you to read http://nyalldawson.net/2016/10/speeding-up-your-pyqgis-scripts/ This will highly speed up your scripts. Instead to query all attributes, with geometry, just query what you need in your scripts.


From Docs, you can pass a QgsFeatureRequest to getFeatures()


QgsFeatureRequest describe the way you retrieve the QgsFeature You can use setSubsetOfAttributes (https://qgis.org/pyqgis/3.0/core/Feature/QgsFeatureRequest.html#qgis.core.QgsFeatureRequest.setSubsetOfAttributes).

The QgsFeatureRequest object that can be pass to getFeatures() has a lot of options. There are describe in the docs. For example you can:

  • Filter features by an extent
  • Filter features by an expression (using QgsExpression)
  • Avoid fetching geometry to improve performance
  • get only a subset of attributes (it's your use case)
  • ...

Plus, all options can be chained (e.g., filter by extent and retrieving only some fields without geometry)

See : https://qgis.org/pyqgis/3.0/core/Feature/QgsFeatureRequest.html

You can find some example using this here


With your help I ended up using a generator like this (for when I forget it):

layer = iface.activeLayer()
fields_to_return = ['kommunkod','lanskod', 'lansnamn']

indexes = [layer.fields().indexFromName(field) for field in fields_to_return]
request = QgsFeatureRequest()

dataGenerator = ([f[fieldname] for fieldname in fields_to_return] for f in layer.getFeatures(request))

for feats in dataGenerator:

#[862.0, 8.0, 'Kalmar län']
#[2460.0, 24.0, 'Västerbottens län']
#[643.0, 6.0, 'Jönköpings län']

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.