I need to return the first record of a feature class as a list. Is this possible? I can't seem to figure it out using row.getValue()
as it does not allow me to put a wildcard in there.
-
1Are you looking to return a list of all the values for each of the fields in 1 list?– dklassenApr 9, 2014 at 17:52
-
What version of ArcGIS are you using, 10.1?– the_skuaApr 9, 2014 at 17:55
-
ArcGIS version 10.0– RustyShacklefordApr 9, 2014 at 17:56
-
I just need the first row as a list, so something like [0,"NJ","123 street"]– RustyShacklefordApr 9, 2014 at 17:57
-
1@wannabe_n00b please edit your question to include this information, as well as what you've tried. This site works best when questions include all necessary details rather than having to fish them out of the comments.– blah238Apr 9, 2014 at 19:09
2 Answers
Give this a try:
import arcpy
ds = "NAME OF DATASET"
fields = [f.name for f in arcpy.ListFields(ds)]
cur = arcpy.SearchCursor(ds)
outlist = []
for row in cur:
for field in fields:
outlist.append(row.getValue(field))
break
-
I basically had this already, I was hoping I didn't need this many lines. BTW, you don't need to do list comprehension in your 4th line if you just do getValue(field.name) Apr 9, 2014 at 18:12
-
5If you already have this - I am not sure what you are looking for then? This works!– dklassenApr 9, 2014 at 18:14
-
1@ian you could do: fields = arcpy.ListFields(ds) then in the cursor simply do field.name, but I prefer my way in this case!– dklassenApr 9, 2014 at 18:45
Since you asked for a 1-liner:
firstRow = next(([row.getValue(field) for field in (f.name for f in arcpy.ListFields(ds))] for row in arcpy.SearchCursor(ds)), None)
This uses a generator expression and the next()
built-in function to short-circuit the evaluation of the generator such that only the first row is fetched. The None
argument avoids a StopIteration
exception from being raised if there are no rows in the dataset.
This is a lot easier in 10.1, BTW (arcpy.da cursors return tuples).
-
2This is what makes Python so cool - so many different approaches to do the same thing! And it gets better all the time.– dklassenApr 9, 2014 at 18:48
-
I was hoping arcpy had a built in that retrieved all attributes but this will have to suffice. Apr 9, 2014 at 20:04
-
2