In the code below, the line 'alias = dict[fld.name]' always throws an exception. I don't see why; printing out fld.name works just fine. Also, the exception message is the field name printing correctly.
Printing the dictionary keys and values also works fine. The ultimate goal is to get a string to set as the field alias using AlterField.
The dictionary seems to be built ok. I can print out key/value pairs with iteritems(). The problem is in accessing the values, using field names returned by arcpy.ListFields, which also print on on their own. I've tried setting the key (fld.name) to a variable, enclosing it in quotes, to no avail. I keep getting an error in the form 'KeyError: u'B01001m1'. B01001m1 is a valid key.
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, '')
dict[row[0]] = fn
# Get list of tables to add alias to
tbls = arcpy.ListTables()
for tbl in tbls:
tblflds = arcpy.ListFields(tbl)
for fld in tblflds:
try:
alias = dict[fld.name] # exception here
print(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)
d = dict(one=2, two=3)
ord = {'one': 2, 'two': 3}
but nod= dict(one)
only – gene Dec 8 '14 at 17:32print d['one']
gives 2. What is the content of fld.name ? – gene Dec 8 '14 at 17:46d= dict(B23009e11='Age:25-44')
the correct result isprint dict['B23009e11']
and notprint dict[[B23009e11]
because B23009e11 is a variable non defined. You cannot make a dictionary withd = {B23009e11:'Age:25-44'}
(you can try in a Python Shell) – gene Dec 8 '14 at 18:20