I have a dBase database file and I'm viewing and editing the table in ArcGIS Pro. I want to use the arcpy.da.SearchCursor function to fill a dictionary and create a key-value pair by iterating through multiple fields and row values in my table. I will eventually use this dictionary to compare key-value pairs from another dictionary and see if items in both lists match.

My first step is to understand and create dictionaries with ArcPy and Python. My goal is to create and fill a dictionary where the key is a shapefile and the value is a list of field names thought to be within the shapefile. The code below creates a key and value pair where the key is a shapefile and the value is a list of row attributes from five fields.

import arcpy

arcpy.env.workspace = r"C:\TestFolder"

dbf = "APExistOnly_Edit.dbf"

myfield = "FI_PATH"

FieldNameDict = {}  

rows = arcpy.SearchCursor(dbf)  
for row in rows:

    FieldNameDict[row.FI_PATH] = [row.AP_ZIP,row.AP_STATE,row.AP_CITY,row.AP_FULLADD,row.AP_BUILDIN] 


With this code I created a dictionary called FieldNameDict and placed the key as field FI_PATH and assigned the row values from each field to a list. Below is the output from the code. When viewing the output, one can see that the lists contain empty elements with no text. This is because some of the fields contain rows with no value.

enter image description here

Currently, I have messy code and logic and I want to see if someone can help with better code. I want to create the dictionary by using arcpy.SearchCursor and iterate through multiple fields and rows. I want to create lists, associated with a key, that do not include empty row elements ' ' . I would like to exclude rows with no text when iterating through fields with the search cursor object.


2 Answers 2


Consider using an arcpy.da.SearchCursor:

FieldNameDict = {}  

with arcpy.da.SearchCursor(dbf,[myfield,'AP_ZIP','AP_STATE','AP_CITY','AP_FULLADD','AP_BUILDIN']) as rows:
    for row in rows:
            FieldNameDict[row[0]] = row[1:] # everything but the first element 

As the row is a tuple that is returned you can use simple indexing [1:] to return everything in the row after the first element (row[0]) and clean up the cursor, releasing locks, when done. Be aware though that if the values of myfield aren't unique the value stored against the key of the preexistent will be overwritten.


I have not tested this but it is a one liner that uses dictionary comprehension, an arcpy.da.SearchCursor() and the indexing syntax from the answer by @MichaelStimson:

FieldNameDict = {row[0]:[row[1:]] for row in arcpy.da.SearchCursor(dbf,[myfield,'AP_ZIP','AP_STATE','AP_CITY','AP_FULLADD','AP_BUILDIN'])}

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.