2

Working in QGIS 3 x64 with built-in python console and editor.

I have a list of the feature IDs of duplicate features in my dataset. Ultimately, I want each of these features to have a value of 1 for the field error.

When I run the following block of code, the correct number of duplicate features prints, so that's not a problem. It's when I go to update error to 1.

Code so far:

geoms = dict()
dup_features = list()
null_features = set()

features = layer.getFeatures()
index = QgsSpatialIndex()

for current, f in enumerate(features):
    if not f.hasGeometry():
        null_features.add(f.id())
        continue

    geoms[f.id()] = f.geometry()
    index.addFeature(f)

unique_features = dict(geoms)

for feature_id, geometry in geoms.items():
    if feature_id not in unique_features:
        continue

    candidates = index.intersects(geometry.boundingBox())
    candidates.remove(feature_id)

    for candidate_id in candidates:
        if geometry.isGeosEqual(geoms[candidate_id]):
            dup_features.append(feature_id)

print(len(dup_features))

## problem section of code

for feature in dup_features:
    feature['error'] = 1 ## Line 58 referred in error
    layer.updateFeature(feature)

Error generated:

    File "<string>", line 58, in <module>
TypeError: 'int' object does not support item assignment

Alternatives Tried: (none of these throw errors but don't update the attribute value)

for feature_id in dup_features:
    layer.getFeature(feature_id)
    feature['error'] = 1
    layer.updateFeature(feature)
for feature_id in dup_features:
    feature['error'] = 1
    layer.updateFeature(feature)
2
  • The code looks ok to me - can you clarify what issue you experience with the code?
    – ndawson
    Jan 15, 2019 at 20:17
  • Updated question, let me know if you still need more clarification
    – jyingling
    Jan 16, 2019 at 14:29

1 Answer 1

1

Once you have some duplicate feature ids stored in your list e.g.

dup_features = [9, 10, 11]

Try replacing those troublesome lines with something like this:

fld_id = layer.fields().lookupField('error')

for feature_id in dup_features:
    fid = feature_id
    atts = {fld_id: 1}
    layer.dataProvider().changeAttributeValues({fid: atts})

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.