# Fill Features of attribute table by using another feature in QGIS

I would like to fill up an attribute table in QGIS for the feature 'Color' based on another feature in the attribute table.

At the moment it looks like this for the features 'Direction' and 'Color':

Direction Color

north none south none east none west none

I would like to fill the Color feature with RGB color codes to directly plot them by using my code. At the moment I only managed to add a new Field for the feature Color (the other features are already implemented). For example if there is North, the color code '0,165,0,255' shall be inserted into the other feature.

# b is the shapefile applied

from PyQt4.QtCore import *
b.updateFields()


• You have a column with directions (N,S,W,E etc.) and want to calculate a new column with RGB values?
– BERA
Aug 14 '20 at 10:43
• Yes exactly (looks like the text was formatted sorry). Based on column 1 I wanna fill up the new one with RGB values Aug 14 '20 at 10:48

You can use a dictionary:

lyr = iface.activeLayer()

d = {'N':'1,1,1',
'S':'2,2,2',
'W':'3,3,3',

dirfield = 'Direction'
rgbfield = 'RGB'

lyr.startEditing()
for f in lyr.getFeatures():
if f[dirfield] in d:
newval = d[f[dirfield]]
else:
newval = '0,0,0'
_=f.setAttribute(f.fieldNameIndex(rgbfield), newval)
_=lyr.updateFeature(f)

lyr.commitChanges()


• I tried to implement your code but it says: name 'edit' is not defined I cannot figure out why. Maybe its because a different version? I use QGIS 2.88 Wien Aug 14 '20 at 11:49
• Try removing it and replace with lyr.startEditing() and then lyr.commitChanges()
– BERA
Aug 14 '20 at 11:54
• 'NoneType' object has no attribute 'startEditing' It seems like lyr is a nonetype which means that my shapefile 'b' is not active aparently. Do I need to extra activate it? Aug 14 '20 at 12:05
• b needs to be a layer, not a path to a shapefile (if it is?). For example: lyr = QgsVectorLayer(r"C:\path\to\shapefolder\someshapefile.shp", "b", "ogr")
– BERA
Aug 14 '20 at 12:08
• I found it, I must put b into it directly instead of lyr. Seems like I already have it active since the beginning and hence just have to directly implement it. Thank you very much for your help! Aug 14 '20 at 12:25