简体   繁体   中英

Adding Keys and Values to Python Dictionary in Reverse Order

I have written a simple script that prints out and adds the name of a table and it's associated column headings to a python list:

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

In each table there are a number of column headings. There are many instances where one or more tables contain the same column headings. I want to do a bit of a reverse python dictionary instead of a list, where keys are the column headings and the values are the table names. My idea is, to find the all the tables that each column heading lies within.

I've been playing around all afternoon and I think I am over thinking this so I came here for some help. If anyone can suggest how I can accomplish this, i would appreciate it.

Thanks, Mike

Try this:

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

If I understand correctly, you want to map from a column name to a list of tables that contain that have columns with that name. That should be easy enough to do with a 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)

I'm not sure if table.name is what you want to save, exactly, but this should get you on the right track.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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