Using arcmap's field calculator I need to programatically loop through all of the entries in the field and for each name it gets its own unique id. So names that are the same would get the same number. This is done through model builder.

def NameReclass(name): foreach name in species .... etc.

I'm just really confused how to do this without if/elif statements and specifying the string name == 1, etc. because it needs to be an id for each name shown.

  • 2
    Please include an example containing original and desired output.
    – Aaron
    Commented Apr 16, 2015 at 19:48
  • Out of curiosity, why is using elif off the table?
    – juturna
    Commented Apr 16, 2015 at 19:57
  • 1
    Several softwares have field calculators, so it might be helpful to specify which one. Is there one entry/word per field, or multiple (ie bird vs bird, rodent)? I believe you'll be wanting to look at either a dictionary or a CASE statement. How many possible words/numbers are there?
    – Chris W
    Commented Apr 16, 2015 at 20:04
  • Use 2 lists, one with possible names, second with matching numbers
    – FelixIP
    Commented Apr 16, 2015 at 20:12

2 Answers 2


You can use the Python setdefault() method and an UpdateCursor to do this.

import arcpy

fc = r'C:\temp\your_shapefile.shp'

# create an empty dictionary
convert = {}

# Start an update cursor and add unique ID based on unique string value
with arcpy.da.UpdateCursor(fc, ["species", "code"]) as cursor:
    for row in cursor:
        row[1] = convert.setdefault(row[0], len(convert))

To illustrate what is going on behind the scenes, setdefault() adds a new key and unique value for every new species it encounters:

>>> str2id
{u'A': 0, u'B': 1, u'C': 2}

enter image description here

  • cool, I didn't know about setDefault(). that looks pretty useful.
    – mr.adam
    Commented Apr 17, 2015 at 16:07

This works:

caseList = [ ]

def returnCase(inValue):
   global caseList

   if not inValue in caseList:

   return caseList.index(inValue)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.