Select to view content in your preferred language

dict(zip()) in for loop with Calc Field codeblock

1786
10
Jump to solution
10-08-2023 02:54 PM
coolflippers
Regular Contributor

Good evening, some trouble with the below example code. This is my first time putting a loop in a function for Calculate Field. I've tried a number of ways (putting brackets after row in the condition of the for loop, putting a 0 inside the brackets, changing the equals sign, trying the brackets with Key, etc).

 

KeyList = ['a','b','c']
ValueList = ['chair','lamp','rug']
Dict = dict(zip(KeyList,ValueList))​
codeblock = """
def output(Key,Value):
    for row in KeyList:
        if row == Key:
            return Dict[KeyList]
        else:
            return Value"""​

 

TableExample:

ID

NAME(NewField)

a

 (chair)
zdesk(desk)
c (rug)

 

arcpy.management.CalculateField(
    in_table = "TableExample",
    field = "NewField",
    expression = "output(!ID!,!NAME!)",
    expression_type = "PYTHON3",
    code_block = codeblock
    )​

 

0 Kudos
10 Replies
DanPatterson
MVP Esteemed Contributor

my line 6...

  • if the id_val is a key in the dictionary, then pull its value and format it for output.
    • I wasn't sure why you wanted ( ) brackets around the output, but I put them in, just remove them if not needed
  • if it isn't, then return None (which will produce a <Null> in the table... this could be replaced with anything you want

... sort of retired...
0 Kudos