A true GIS layer contains both spatial geometry and database attributes. In this recipe, we'll access a vector point layer's attributes in PyQGIS. We'll use a file-based layer from a shapefile, but once a layer is loaded in QGIS, every vector layer works the same way.
Once again, we'll use the same New York City Museums layer from the Loading a vector layer from a file recipe in this chapter. You can download the layer from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Unzip that file and place the shapefile's contents in a directory named nyc
within your qgis_data
directory, within your root or home directory.
In the following steps, we'll load the layer, access the features
iterator, grab the first feature, and then view the attributes as a Python list:
First, load the shapefile as a vector layer:
layer = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "New York City Museums", "ogr")
Next, get the features...