Thanks Joshua. I changed the name of the dictionary to dictflds. The error I get if I try to access the value outside of the try block is KeyError: u'B01001e1', and the error when in the try block reads Line 45, B01001e1, where the line number is wherever I first try to access the dictionary value and B01001e1 is a valid field name. It's not that particular value that's a problem; the error occurs for every field. I've tried enclosing it in str(), setting it to a variable both when accessing it and setting the key, no luck. If I just print fld.name, works fine. Full code (minus header comments) below.
import arcpy, os
from arcpy import env
env.workspace = r'K:\Projects\Other Depts\Planning\Lori_Census\Census.gdb'
def main():
metatable = 'BG_Metadata_2012'
metaflds = ('Short_Name', 'Full_Name')
est = '--(Estimate)'
moe = 'Margin of Error'
dictflds = {}
# Get dictionary of short names and corresponding full names from metadata
# table, skipping moe fields and removing whitespace and estimate text from
# full name.
with arcpy.da.SearchCursor(metatable, metaflds) as rows:
for row in rows:
if not moe in row[1]:
fn = row[1].replace(' ', '')
fn = fn.replace(est, '')
dictflds[row[1]] = fn
for k, v in dictflds.iteritems()
print(' : '.join([k, v]) # works fine
# Get list of tables to add alias to
tbls = arcpy.ListTables()
for tbl in tbls:
tblflds = arcpy.ListFields(tbl)
for fld in tblflds:
try:
print(fld.name) # works fine
alias = dictflds[fld.name] # exception raised here
print(alias)
print(' : '.join[tbl, fld.name, alias])
arcpy.AlterField_management(tbl, fld, new_field_alias=alias)
except Exception as e:
import traceback
import sys
tb = sys.exc_info()[2]
print('Oh no!')
print("Line {0}".format(tb.tb_lineno))
print(e.message) # this prints the fld.name value
if __name__ == '__main__':
main()