[GIS] Print values from Tables in QGIS Console

printingpyqgisqgisqgis-python-console

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]
>>>iface.setActiveLayer(vl)

Example 1:

>>>print vl

Output:

>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()
>>>fields.toList()

Output:

[<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.

Best Answer

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