Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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)

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')

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:

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


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.