Select to view content in your preferred language

Variable_from_excel.py

2232
2
08-20-2014 04:44 AM

Variable_from_excel.py

Tags (1)
Attachments
Comments
XanderBakker
Esri Esteemed Contributor

Some pointers...

  • You don't need to use "gp = arcgisscripting.create()". Arcpy come with "AddMessage" too
  • You can use the "index" method on a list to get the index (will raise an error if the key field is not found)
  • Replace the dictionary.has_key(key) for key in dictionary. This adds to the readability
  • Will omit any field placed on the left of the ID field.

import arcpy

def Message(sMsg):

    print sMsg

    arcpy.AddMessage(sMsg)

# configuration

table = "C:\Users\deenr\Desktop\Data.xlsx\Sheet1$"

keyField = "ID"

fields = [fld.name for fld in arcpy.ListFields(table)]

fIdx = fields.index(keyField)

dictionary = {}

with arcpy.da.SearchCursor(table, ("*")) as cursor:

    for row in cursor:

        idx = 0

        for cell in row:

            if idx == fIdx:

                if not str(cell) in dictionary:

                    dictionary[str(cell)] = []

            else:

                if str(row[fIdx]) in dictionary:

                    dictionary[str(row[fIdx])].append(cell)

            idx += 1

# Print whole dictionary

Message(str(dictionary.items()))

for key in dictionary.keys():

    # Print Values

    Message(str(dictionary[key]))

Kind regards, Xander

RiyasDeen
Frequent Contributor

Hi Xander,

Thanks for the pointers, should agree your code looks more elegant than mine.

Regards

Riyas Deen

Version history
Last update:
‎08-20-2014 04:44 AM
Updated by:
Contributors