I want to know how to get the QGIS Console to print out actual values pertaining to a Layer's attribute table (e.g. field names, feature values, etc.).

So far using the "print" command all I'm able to get are object references.

The next 2 examples involve a shapefile of mine called 'Province', and are predicated by the following code:

>>>vl = QgsMapLayerRegistry.instance().mapLayersByName('Province')[0]

Example 1:

>>>print vl


>qgis._core.QgsVectorLayer object at 0x11f24a348<

A vector layer object reference is returned, but I want the actual name of the layer, which of course is 'Province'.

Example 2:

>>>fields = vl.pendingFields()


[<qgis._core.QgsField object at 0x11f24a770>, <qgis._core.QgsField object at 0x11f24aa68>, <qgis._core.QgsField object at 0x11f24ab00>, <qgis._core.QgsField object at 0x11f24ab98>, <qgis._core.QgsField object at 0x11f24ac30>, <qgis._core.QgsField object at 0x11f24acc8>

Granted, I used "toList()" rather than "print", but the result is the same: rather than the actual names of the fields I get an array of object references.

How do you tell Console to give you the actual values that you happen to be storing in a given variable, rather than the object refs?

Much obliged.


You need to access the attributes of the features of the table.

lyr = iface.activeLayer()

features = lyr.getFeatures()

for ft in features:
    attrs = ft.attributes()
    print attrs

To access first column use

print attrs[0]

Column names can be add with:

lyr = iface.activeLayer()

features = lyr.getFeatures()
field_names = [field.name() for field in lyr.pendingFields() ]

for ft in features:
    print dict(zip(field_names, ft.attributes()))

Just to add to @Jakob's brilliant answer, you can use name() to print the name of the layer:

vl = QgsMapLayerRegistry.instance().mapLayersByName('Province')[0]
print vl.name()

If you have multiple layers loaded, you can use the for loop which identifies the first layer found, prints the name, then repeats for any subsequent layers:

layers = QgsMapLayerRegistry.instance().mapLayers().values()
for layer in layers:
    print layer.name()

Hope this helps!

  • 1
    Great tip! Much appreciated!
    – Waterman
    Oct 27 '15 at 11:31
  • @user3309182 - Most welcome buddy :)
    – Joseph
    Oct 27 '15 at 11:32

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.