Using an external Dictionary that multiple scripts in model builder can reference for a reclass

275
1
01-04-2022 11:02 AM
PatrickAllen42
New Contributor

Hello All, first time asking a question, thanks for your help in advance

I am using one field in order to fill another field in model builder.  Now most of this rename just uses the first word of the name to fill the second and that is done in a previous step.  Where it uses this script is when that method doesn't work and it needs a particular name for the starting name.  The way that I do this now is with the script below but since I do this same process multiple times on different datasets I have to update the list in multiple places in the model.  What I would like to do is have a single dictionary with all the name pairs that all the separate scripts can reference, something like a CSV as a dictionary with each name pair.  Is this possible?  

FEILD NAME
ShortNameField

EXPRESSION
reclass( !LongNameField!, !ShortNameField! )

CODE BLOCK
def reclass( LongNameField,ShortNameField 😞

if (LongNameField == "LONG NAME 1"):
return "LN 1"
elif (LongNameField == "LONG NAME 2"):
return "LN 2"
elif (LongNameField == "LONG NAME 3"):
return "LN 3"
elif (LongNameField == "LONG NAME 4"):
return "LN 4"
[etc for hundreds of names]
else:
return ShortNameField

0 Kudos
1 Reply
by Anonymous User
Not applicable

You can use the dictionaries get() method.  It returns either the matching key's value or the default ShortNameField if the LongNameField is not matched to a key:

 

nameDict = {"LONG NAME 1": "LN 1", "LONG NAME 2": "LN 2", "LONG NAME 4": "LN 4"}

val = nameDict.get(LongNameField, ShortNameField)

 

edit to add: You can read a csv to a dictionary fairly easy, (lots of examples out there) setting a column as key and the other column as its value for each row.

with open('your.csv', mode='r') as infile:
    reader = csv.reader(infile)
    nameDict = dict((rows[0],rows[1]) for rows in reader)