2

I am using Python 3 in ArcGIS Pro. In plain English, my goal is calculate one field in a table using a list of values from another field. I can do this with a long list of if statements, but I can't figure out the syntax to do it with lists (and maybe for loops?).

For example, let's say I have two lists:

veg = ['Carrot', 'Celery', 'Broccoli']
fruit = ['Apple', 'Banana', 'Grape']

I would essentially like to ask..."If the field contains a value from the list 'veg', return 'Vegetable', else if the field contains a value from list 'fruit', return 'Fruit', else leave null"

I know this is possible I am just having trouble with the syntax. I would like to avoid doing this ad nauseum:

if FIELD == 'Carrot':
return 'Vegetable
elif FIELD == 'Celery':
return 'Vegetable'

I know it's possible I am just struggling with the syntax. I am reducing ~40 values in one field to 2 values in another.

8

You can use in to check for membership:

if FIELD in veg:
    return 'Vegetable'
elif FIELD in fruit:
    return 'Fruit'

For bonus points use sets, which offer better performance for this:

veg = {'Carrot', 'Celery', 'Broccoli'}
fruit = {'Apple', 'Banana', 'Grape'}
| improve this answer | |
2

I always prefer to use an UpdateCursor to update feature attributes, mainly because I find the syntax more readable and Esri has gone a long way in optimizing cursor performance. I would also recommend using the .lower() method to make sure case does not matter when checking your check lists. For example:

import arcpy

fc = r'C:\path\to\your\geodatabase.gdb\featureclass'

veg = ['Carrot', 'Celery', 'Broccoli']
fruit = ['Apple', 'Banana', 'Grape']

with arcpy.da.UpdateCursor(fc, ['produce_field', 'new_field']) as cursor:
    for row in cursor:
        if row[0].lower() in (x.lower() for x in veg):
            row[1] = 'Vegetable'
        elif row[0].lower() in (x.lower() for x in fruit):
            row[1] = 'Fruit'
        cursor.updateRow(row)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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