Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

Hi: I am trying to create a function to update multiple fields based on different criteria. I want to pass the field name and condition thru' a dictionary (please see the function description in the enclosed code).

def CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition):
  '''
  fieldNames_Condition = {'TestID': '"LOC-"+(row.getValue("OBJECTID"))',
                          'UPADATED':'Yes'} 

  usage: CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition)
  '''
  try:
    rows=arcpy.UpdateCursor(sourceTable)
    for row in rows:
      for fieldName, condition in fieldNames_Condition.iteritems():
        row.setValue(fieldName,condition)
        rows.updateRow(row)
    del row, rows

  except Exception, e:
    import traceback, sys
    tb = sys.exc_info()[2]
    print "Line %i" % tb.tb_lineno
    print e.message

I am working with Python 2.6.5, Arcpy 10 and Win 7 64 and the sourceTable is a FileGDB Featureclass.

I would like to get the result of TestID field as "LOC-101" where 101 is the value of the ObjectID field. If I run this now-it'll write the condition as such as it's treated as a string. How can I parse the condition as a non string item?

Any help is appreciated!!! Thanks in advance!!

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

If you have a string that contains Python code you want to run, you can use the Python Built-In Function exec.

In your case what you could do is:

def CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition):
'''
fieldNames_Condition = {'TestID': 'id = "LOC-" + str(row.getValue("OBJECTID"))',
                        'UPADATED':'Yes'} 

usage: CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition)
'''
try:
  rows=arcpy.UpdateCursor(sourceTable)
  for row in rows:
    for fieldName, condition in fieldNames_Condition.iteritems():
      exec(condition)
      row.setValue(fieldName,id)
      rows.updateRow(row)
  del row, rows

except Exception, e:
  import traceback, sys
  tb = sys.exc_info()[2]
  print "Line %i" % tb.tb_lineno
  print e.message

This should execute the row.getValue code in your condition and return a new variable id. Then, you can use id in your row.setValue.

Here is a simpler example of exec:

x = 'y = "LOC" + str(2*5)'
exec(x)
print y # should return "LOC10"
share|improve this answer
    
Perfect Solution!! You saved my day!!!!! Thank you very much. –  Ann May 16 '13 at 15:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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