Editing features from an existing layer

You can now add and delete features, but sometimes you only need to change an attribute value. For example, an open case status to a closed case status. In this section, you will learn how to modify attributes.

Attributes are modified by calling changeAttributeValues(). The following code changes a single feature:

scf.dataProvider().changeAttributeValues({114:{0:123,1:345,2:"ADA",3:"NEW"} })

The previous code calls changeAttributeValues() and passes a dictionary with the key being the feature id and the value being a dictionary of attributes—{id:{0:value, 1:value, n:value}}. The keys for the attributes dictionary are the field indexes. There are four fields in the features so the dictionary of attributes will have keys 0 through 3. The following screenshot shows the change in the attribute table:

A single feature edited

The previous example assumes you already know the id of the feature you want to modify. It also assumes you want to modify all of the attribute values. The following code will modify several features but only a single attribute value in each—Status:

attributes={3:"Closed"}
for x in scf.getFeatures():
if x["Type"]=='Other':
scf.dataProvider().changeAttributeValues({x.id():attributes})

In the previous code, a dictionary is declared with a key of 3 (the 'Status' field) and a value of "Closed". The code then iterates through the features in the layer looking for a match. When it finds a match, it changes the attribute value, but this time only the value of the Status field. The results are reflected in the attributes table shown in the screenshot as follows:

All features of the Other type now have a status of Open

In the previous examples, you have been iterating through features and selecting them based on a condition. In the next section, you will learn how to highlight the selected features and how to use expressions to select instead of a condition.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset