在Python字典中添加键和值的反向Ord

2024-06-23 03:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

谢谢, 迈克


Tags: namein脚本名称标题field列表for
3条回答

如果我理解正确的话,您希望从一个列名映射到一个表列表,该表包含具有该名称的列。使用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是否是您想要保存的内容,但这应该会让您走上正确的轨道。在

要创建一个字典,其中每个键都是字段名,每个值都是表名的列表:

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

然后,如果需要包含字段LastName的表的列表:

^{pr2}$

如果使用的数据库对列名不区分大小写,则可能需要转换字段名称在测试字典之前先大写。在

试试这个:

result = {}
for table in arcpy.ListTables():
    for field in arcpy.ListFields(table):
        result.setdefault(field.name, []).append(table)

相关问题 更多 >

    热门问题