0

我编写了一个简单的脚本,它打印出一个表的名称并将其关联的列标题添加到 python 列表中:

for table in arcpy.ListTables():
    for field in arcpy.ListFields(table):       
        b.append(field.name + "," + fc)
print b

在每个表中都有许多列标题。在许多情况下,一个或多个表包含相同的列标题。我想做一些反向 python 字典而不是列表,其中键是列标题,值是表名。我的想法是,找到每个列标题所在的所有表格。

我整个下午都在玩,我想我想太多了,所以我来这里寻求帮助。如果有人能建议我如何做到这一点,我将不胜感激。

谢谢,迈克

4

3 回答 3

1

尝试这个:

result = {}
for table in arcpy.ListTables():
    for field in arcpy.ListFields(table):
        result.setdefault(field.name, []).append(table)
于 2013-09-11T23:01:54.970 回答
0

You want to create a dictionary in which each key is a field name, and each value is a list of table names:

 # initialize the dictionary
 col_index = {}

 for table in arcpy.ListTables():
     for field in arcpy.ListFields(table):
         if field.name not in col_index:
              # this is a field name we haven't seen before,
              # so initialize a dictionary entry with an empty list
              # as the corresponding value
              col_index[field.name] = []
         # add the table name to the list of tables for this field name
         col_index[field.name].append(table.name)

And then, if you want want a list of tables that contain the field LastName:

 list_of_tables = col_index['LastName']

If you're using a database that is case-insensitive with respect to column names, you might want to convert field.name to upper case before testing the dictionary.

于 2013-09-12T00:56:18.767 回答
0

如果我理解正确,您希望从列名映射到包含具有该名称的列的表列表。这应该很容易做到defaultdict

from collections import defaultdict

header_to_table_dict = defaultdict(list)

for table in arcpy.ListTables():
    for field in arcpy.ListFields(table):
        header_to_table_dict[field.name].append(table.name)

我不确定table.name您是否要准确保存,但这应该让您走上正轨。

于 2013-09-11T23:02:02.030 回答