繁体   English   中英

以相反的顺序向Python字典添加键和值

[英]Adding Keys and Values to Python Dictionary in Reverse Order

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

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

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

我整个下午都在玩,我想我已经考虑得太过了,所以我来这里寻求帮助。 如果有人可以建议我如何实现这一目标,我将不胜感激。

谢谢,迈克

尝试这个:

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

如果我理解正确,则希望从列名映射到包含具有该名称列的表的列表。 使用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的表的列表,请执行以下操作:

 list_of_tables = col_index['LastName']

如果使用的数据库的列名不区分大小写,则可能需要在测试字典之前将field.name转换为大写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM