Select to view content in your preferred language

UpdateCursor with domain value

458
1
08-31-2022 06:33 PM
JohnConnor01
Occasional Contributor

Hello,

I was given a .csv with data to update in the database. The csv is just an export from ArcGIS and data updates were made in that spreadsheet. I've done this before using arcpy, but the values in this csv are NOT the coded values this time: they are the actual text domain value. I was thinking I could make a dictionary possibly to do this so... for each attribute field, find the domain it uses, then find all domain codes and the their text value matches. Then if they were in a dict, I could call the domain text value to get the associated coded value domain. I'm getting so lost in the loops. Also, lots of examples I see online use .gdbs, I use an .sde connection.

I would be so grateful for any help - afraid I'm about to lose my job.

Thank you!!

-JC from Boston

0 Kudos
1 Reply
JohannesLindner
MVP Frequent Contributor
in_table = r"N:\bla\bla\connection.sde\DataOwner.Table"

# get a dictionary of relevant domains values
from pathlib import Path
all_domains = {d.name: d for d in arcpy.da.ListDomains(Path(in_table).parent)}
encode_dict = {
    f.name: {v: k for k, v in all_domains[f.domain].codedValues.items()}
    for f in arcpy.ListFields(in_table) if f.domain}
# {DomainField1: {Desc1: Code1, Desc2: Code2}, DomainField2: ...}

# function to return "true" values
def get_true_value(field_name, value):
    try:
        return encode_dict[field_name][value]
    except KeyError:
        return value


fields = ["Field1", "Field2", "Field3"]
key_field_index = 0  #Field1

# read the imported csv
csv_rows = {row[key_field_index]: row for row in arcpy.da.SearchCursor("CsvTable", fields)}

# update the original table
with arcpy.da.UpdateCursor(in_table, fields) as cursor:
    for row in cursor:
        try:
            key = row[key_field_index]
            new_row = list(csv_rows[key])
            for i, f in enumerate(fields):
                new_row[i] = get_true_value(f, new_row[i])
            cursor.updateRow(new_row)
        except KeyError:
            print(f"Key {key} not found in update table.")

Have a great day!
Johannes