[GIS] Calculating unique ID value for a field in QGIS using python

pythonqgisunique id

I am trying to calculate a unique ID field for a vector layer in qgis, using python. I found some code to calculate attribute values, and tried to increment the value in the expression, but it doesn't work – it calculates all feature values as 0. I'm guessing the intial value I set for the expression is what it is reading each time – it doesn't seem to change it inside the loop. Anyone have any ideas? Here is my code:

QgsMapLayerRegistry.instance().addMapLayer(dsslvExplodeLyr)

idx = dsslvExplodeLyr.fieldNameIndex('UniqueID')

eVal = '0'
e = QgsExpression(eVal)
e.prepare(dsslvExplodeLyr.pendingFields())

dsslvExplodeLyr.startEditing()

for f in dsslvExplodeLyr.getFeatures():
    num = int(eVal)
    num = num + 1
    eVal = str(num)     
    f[idx] = e.evaluate(f)
    dsslvExplodeLyr.updateFeature(f)

dsslvExplodeLyr.commitChanges()

I should mention I've also tried '$rownum' for the expression as that works in the field calculator gui but it also just gives a value of 0.

Best Answer

This code works well (fillFields function) and it is not requiered the start editing operating.

def fillFields(list, idx):
    i =0
    for item in list:
        new_values = {idx:item }
        provider.changeAttributeValues({i: new_values})
        i += 1

from PyQt4.QtCore import *

dsslvExplodeLyr = iface.activeLayer()

provider = dsslvExplodeLyr.dataProvider()

idx = dsslvExplodeLyr.fieldNameIndex('UniqueID')

n= dsslvExplodeLyr.featureCount()  #count features

field1 = range(n)   #create list with n values

fillFields(field1, idx)  #introduce list 'field1' in field with index of 'UniqueID'

I used your nomenclature for the layer name (dsslvExplodeLyr; a point vector layer) and its field name (UniqueID). The script changed aleatory values between -10 and 10 into this field to integer values between 0-24.

Before running the code in the Python Console:

enter image description here

After running the code

enter image description here