Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

What is the way to get the information contained in the attribute table, say in column 2, row 2 using pyQgis?

share|improve this question

2 Answers 2

To loop over every feature in a layer, use the getFeatures() generator. This returns an iterator of features (QgsFeature) in the layer.

for feature in layer.getFeatures():
    pass # do something with feature

If you're only interested in a particular feature, instead of all of the features in the layer, you can access it using a QgsFeatureRequest and it's FID:

fid = 1 # the second feature (zero based indexing!)
iterator = layer.getFeatures(QgsFeatureRequest().setFilterFid(fid))
feature = next(iterator)

Once you have a QgsFeature object you can use the attributes() method to retrieve the attributes (a.k.a. columns or fields) associated with that feature (a.k.a. row), e.g.:

# get the feature's attributes
attrs = feature.attributes()
# print the second attribute (note zero based indexing of Python lists)
print(attrs[1])

If you want to index the field by it's name, rather than a number, you need to use the field mappings:

idx = layer.fieldNameIndex('name')
print(feature.attributes()[idx])

The field index shouldn't change during the loop, so you only need to call it once.

There is more information and examples in the PyQGIS cookbook: http://www.qgis.org/pyqgis-cookbook/vector.html#iterating-over-vector-layer

share|improve this answer

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

Thought I would actually add some code, as googling this problem returns this question... most people prefer a quick explanation or a code snippet to a link that leads to a page that has a lot of additonal information.

In order to get the information in a table you would first have to access the layer's features. In my case I put the features in a variable. Then you loop through the features, and for each feature you call its attributes, which can then be printed using their column index. For example, if I would like to get all the values in the second column, then I would do this:

lyr = iface.activeLayer()

features = lyr.getFeatures()

for feat in features:
    attrs = feat.attributes()
    print attrs[1]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.