The process to change an attribute in a feature is straightforward and well-supported by the PyQGIS API. In this recipe, we'll change a single attribute, but you can change as many attributes of a feature as desired at once.
You will need the New York City museums' shapefile used in other recipes, which you can download as a ZIP file from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Extract this shapefile to /qgis_data/nyc
.
We will load the shapefile as a vector layer, validate it, define the feature IDs of the fields we want to change, get the index of the field names that we will change, define the new attribute value as an attribute index and value, and change the feature in the layer. To do this, we need to perform the following steps:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
fid1 = 22 fid2 = 23
tel = vectorLyr.fieldNameIndex("TEL") city = vectorLyr.fieldNameIndex("CITY")
attr1 = {tel:"(555) 555-1111", city:"NYC"} attr2 = {tel:"(555) 555-2222", city:"NYC"}
vectorLyr.dataProvider().changeAttributeValues({fid1:attr1, fid2:attr2})
Changing attributes is very similar to changing the geometry within a feature. We explicitly name the feature IDs in this example, but in a real-world program, you would collect these IDs as a part of some other process output, such as a spatial selection. An example of this type of spatial selection is available in the Filtering a layer by Geometry recipe, in Chapter 2, Querying Vector Data.