Defining features in a list

Dave Angel d at davea.name
Fri Sep 7 11:55:02 EDT 2012


On 09/07/2012 11:21 AM, M Whitman wrote:
> Dave- By features I was refering to items in the list.  For background the arcpy module is used for geoprocessing of geographic information.  I'm using my script to get totals for features in a dataset that I receive on a regular basis- for example total number of hydrants, total number of hydrants with null or missing attributes, and total number of hydrants with outlining attributes.
>
> I am experienced particularly with the arcpy module and I am trying deligently to become more experienced with Python in general.  My goal is to fetch values by name and then print output by name. print WS_Hyd and then see "484".   I have some experience with class definition but a dictionary might be the way to go.  I was understanding the response of the Arcpy module but hadn't understood why the list wasn't being defined in my previous loop statement.

There is a list fclist being defined, just before the loop.  But that
list contains the names of the "features" not the values.  So if you
wanted, you could make a second list containing the values, or you could
even make a list containing tuples with name & value.  But assuming
there's no particular ordering you care about, that's what a dictionary
is good at.

In either case that loop is not creating extra variables with names like
WS_Hyd.  Creating variables with arbitrary names from data can only be
done with code that's dangerous and prone to injection attacks.  You can
avoid the problem by putting them in some namespace, either a
dictionary, or a namedtuple, or a custom class.

>   I appreciate the response.  I will look into dict if you have a class definition suggestion I will run with that.  Thanks

Anyway, once you have the dictionary, you can indeed work on the values
in it, in various ways.

table = {}

fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
    table[fc] = +str(arcpy.GetCount_management(fc).getOutput(0))



Now you can use your captured data to do further processing.  Simplest example printing.  Suppose order doesn't matter:

for key in table.iterkeys():
    print key, "=", table[key]

You could also do this as:

for key, value in table.iteritems():
    print key, "=", value

If you want them in the original order, you can use your fclist, which is a list of keys:

for key in fclist:
    print key, "=", table[key]

And of course if you want any particular one, you can do

print table["WS_hyd"]

Note that in the last case, if you typed the literal key wrong, or if the arcpy removed or renamed one of the keys, you'd get an exception there.  To avoid that, you might do something like:

key = "WS_hyd"
if key in table:
    print table[key]


-- 

DaveA




More information about the Python-list mailing list