I'm stuck, on what I'm sure is something simple, but I'm just going around in circles now. The following code is a snippet of a script that iterates over some values I've entered into lists and dictionaries and produces text files that I can feed into another program. The problem I'm having is when attempting to loop round the Direction list and have corresponding values from the relevant dictionary print to file I get the following error:
TypeError: string indices must be integers, not str
Direction = ('E', 'NE')
E = {
'InitialHeading': 0,
'InitialX': 22.480,
'InitialY': 0.000,
'ActiveCurrent': '10y_Current_W'}
NE = {
'InitialHeading': 45,
'InitialX': 15.896,
'InitialY': 15.896,
'ActiveCurrent': '10y_Current_SW'}
casenumber = 0
for Offset in Direction:
# CREATE INDIVIDUAL TEXT FILES
casenumber = casenumber + 1
filename = 'Case%.3d.txt' % casenumber
f = open(filename, 'w')
print >>f, 'InitialHeading: ', Offset['InitialHeading']
print >>f, 'InitialX: ', Offset['InitialX']
print >>f, 'InitialY: ', Offset['InitialY']
print >>f, 'ActiveCurrent: ', Offset['ActiveCurrent']
f.close()
If I replace Offset with the name of the dictionary so the line reads as follows:
print >>f, 'InitialHeading: ', E['InitialHeading']
Then the output is exactly what I want and I know that Offset is equal to E when I run the file, as I added a line to print the value of Offset to the console window.
Why doesn't it recognise the dictionary name when it's the same value as the variable Offset, which is obtained from the Direction list? This piece of code is from nested for loops, so I need to be able to refer to the lists & dictionaries to obtain the values, rather than a more manual alternative.
解决方案
You are using subscription syntax on the Offset variable, which is a string, taken from Direction.
You cannot use the string in Offset as a placeholder for the variable with the same name directly. Instead, *store the dictionary:
E = {
'InitialHeading': 0,
'InitialX': 22.480,
'InitialY': 0.000,
'ActiveCurrent': '10y_Current_W'}
NE = {
'InitialHeading': 45,
'InitialX': 15.896,
'InitialY': 15.896,
'ActiveCurrent': '10y_Current_SW'}
Direction = (E, NE)
or better still, use another dictionary to wrap the directions:
Direction = {
'E': {
'InitialHeading': 0,
'InitialX': 22.480,
'InitialY': 0.000,
'ActiveCurrent': '10y_Current_W'},
'NE': {
'InitialHeading': 45,
'InitialX': 15.896,
'InitialY': 15.896,
'ActiveCurrent': '10y_Current_SW'}
}
Now you can loop over that dictionary and have both a string name for the direction and the settings associated with it:
for direction, settings in Directions.items():
# CREATE INDIVIDUAL TEXT FILES
casenumber = casenumber + 1
filename = 'Case%.3d.txt' % casenumber
with open(filename, 'w') as f:
print >>f, 'InitialHeading: ', settings['InitialHeading']
print >>f, 'InitialX: ', settings['InitialX']
print >>f, 'InitialY: ', settings['InitialY']
print >>f, 'ActiveCurrent: ', settings['ActiveCurrent']