Creating a list of tuples from arcpy.ListFields()

1048
3
Jump to solution
06-02-2020 11:27 AM
JoeBorgione
MVP Emeritus

I'd like to create a list of tuples where each tuple contains the data from the fields of one feature class: the objective is to iterate through the list and add fields of the name, type and length provided in each of the tuples to a different feature class.  I've hit a snag and I'm sure how to un-snag myself:

fc = r'C:\path\to_gdb\featureClass'
fieldList = []
for f in arcpy.ListFields(fc):
    x = (f'("{f.name}","{f.type}",{f.length})')
    fieldList.append(x‍‍‍‍‍‍‍‍)‍‍‍‍

works pretty good, but not quite perfect.  Each of the tuples is bounded by single quotes so if I try to use the tuple indexes to extract a tuple element, things head south:

fieldList
Out[79]: 
['("OBJECTID","OID",4)',
 '("SHAPE","Geometry",0)',
 '("siteaddid","String",20)',
 '("addressptid","String",20)',
 '("rclnguid","String",254)',
 '("discrpagid","String",75)',
 '("preaddrnum","String",5)',
 '("addrnumsuf","String",5)',
  ...]

I can cheat (and I have) and just copied and pasted fieldList to notepad and deleted the single quotes, but that's using a hammer; how would I create a clean list of tuples without the bounding single quotes:

cleanList
Out[82]: 
[('OBJECTID', 'OID', 4),
 ('SHAPE', 'Geometry', 0),
 ('siteaddid', 'String', 20),
 ('addressptid', 'String', 20),
 ('rclnguid', 'String', 254),
 ('discrpagid', 'String', 75),
 ('preaddrnum', 'String', 5),
 ('addrnumsuf', 'String', 5),
  ...]
That should just about do it....
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

Why are you building a string representation of a tuple:

x = (f'("{f.name}","{f.type}",{f.length})')

instead of just building a tuple:

x = (f.name,f.type,f.length)

View solution in original post

0 Kudos
3 Replies
JoshuaBixby
MVP Esteemed Contributor

Why are you building a string representation of a tuple:

x = (f'("{f.name}","{f.type}",{f.length})')

instead of just building a tuple:

x = (f.name,f.type,f.length)
0 Kudos
DanPatterson
MVP Esteemed Contributor

F (orget) the f-strings.  Remember they are always going to produce a string output.


... sort of retired...
0 Kudos
JoeBorgione
MVP Emeritus

Typical Joe blunder.  That's why I needed a couple extra set of eyes....

That should just about do it....
0 Kudos