Stacked Label using If/Else in a Label Expression

I have a large set of data with lab results that I'm looking to label in ArcMap. I'm trying to build a label expression that needs to produce a label that essentially needs to look like this:

B=5
T=10
E=200

So if B [BEN] is >= to 5, it will produce text that is bolded and red. If B is < 5, it will come out green, and if it is anything else it will come out B=ND. This is the code I have so far to do that, and it works:

def FindLabel ([BEN]):

if float([BEN]) >= 5:
return "<CLR red='255'><FNT size = '8'><BOL>" + "B=" + [BEN] + "</BOL></FNT></CLR>"

elif float([BEN]) < 5:
return"<CLR green='255'><FNT size = '8'>" + "B=" +  [BEN] + "</FNT></CLR>"

else:
return  "<CLR green='255'><FNT size = '8'>" + "B=ND" + "</FNT></CLR>"

The problem is that I also need to do this for compounds T, E, and so on...If I didn't want to use the if/else it would be simple, I could use something like:

return "B=" + [BEN] + "\n" + "E=" + [ETH] + "\n" + "T" + [TOL] + "\n" + "I=" +  [ISO]

I basically need to have stacked labels (as shown above) while using the If/Then statements, and I'm really blanking on how to do this.

• Do you only want to show the stacked label variable if there is a particular value, or will you always have B, then T, then E, and just the formatting will be different based on the value? – evv_gis Mar 15 '17 at 20:09
• @evv_gis I will always have B, T, and E...however, they will be formatted differently based on their value. – Tom Mar 15 '17 at 21:23

You could try something like the following.

def FindLabel ([BEN],[ETH],[TOL],[ISO]):

vars = {"B":[BEN],"E":[ETH],"T":[TOL],"I":[ISO]}
labelStrings = []

for k,v in vars.items():
if float(v) >= 5:
labelStrings.append("<CLR red='255'><FNT size = '8'><BOL>{0}={1}</BOL></FNT></CLR>".format(k,v))
elif float(v) < 5:
labelStrings.append("<CLR green='255'><FNT size = '8'>{0}={1}</FNT></CLR>".format(k,v))
else:
labelStrings.append("<CLR green='255'><FNT size = '8'>{0}=ND</FNT></CLR>".format(k))
return "\n".join(labelStrings)

Just a thought, There is no error checking in this code so if you have a string that cannot be converted to a float you will have issues

If they are constants which you compare them to you can try this (I used arbitrary constants for the comparing values):

def FindLabel ([BEN],[ETH],[TOL],[ISO]):

vars = {"B":[BEN],"E":[ETH],"T":[TOL],"I":[ISO]}
varConstants= {"B":5,"E":6,"T":20,"I":50}
labelStrings = []

for k,v in vars.items():
if float(v) >= varConstants[k]:
labelStrings.append("<CLR red='255'><FNT size = '8'><BOL>{0}={1}</BOL></FNT></CLR>".format(k,v))
elif float(v) < varConstants[k]:
labelStrings.append("<CLR green='255'><FNT size = '8'>{0}={1}</FNT></CLR>".format(k,v))
else:
labelStrings.append("<CLR green='255'><FNT size = '8'>{0}=ND</FNT></CLR>".format(k))
return "\n".join(labelStrings)