0

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.

5
  • 1
    Are you looking to return a list of all the values for each of the fields in 1 list?
    – dklassen
    Apr 9, 2014 at 17:52
  • What version of ArcGIS are you using, 10.1?
    – the_skua
    Apr 9, 2014 at 17:55
  • ArcGIS version 10.0 Apr 9, 2014 at 17:56
  • I just need the first row as a list, so something like [0,"NJ","123 street"] Apr 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.
    – blah238
    Apr 9, 2014 at 19:09

2 Answers 2

7

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
3
  • 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
  • 5
    If you already have this - I am not sure what you are looking for then? This works!
    – dklassen
    Apr 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!
    – dklassen
    Apr 9, 2014 at 18:45
5

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).

3
  • 2
    This is what makes Python so cool - so many different approaches to do the same thing! And it gets better all the time.
    – dklassen
    Apr 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
    As I mentioned, at 10.1 and up it does with arcpy.da cursors.
    – blah238
    Apr 9, 2014 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.