Simple question here, I have
- a dictionary twodee with waternumbers as keys and residence times as values
- when the waternumber matches the value in column two (line.split()[1]) I want to overwrite the value in column 9 of fileName2 with the value of the dictionary
I’ve been trying for like a half hour now and it seems a bit basic to post but maybe it will help someone else out in the future.
twodee = dict(zip(waternumber, residencetime))
with open(fileName2, "r") as otherinput:
try:
for line in otherinput:
for waternumber, residencetime in twodee.iteritems():
line.split()[1] == waternumber
line.split()[9] = residencetime
except:
pass
Thanks very much!
You are not assigning the result of the
.split()to anything, nor are you testing correctly. Moreover, you don’t need to loop over your twodee dict at all, simply test if thewaternumbervalue is present in the dict with theinoperator:Last but not least, you want to actually do something with the changed line, here I print it.
To elaborate a little, your two lines with
.split()in them are operations that end up doing nothing:The first operation splits the line to a list, selects the first elements and tests if that is equal to the
waternumbervalue. This’ll be eitherTrueorFalse, but you don’t do anything with than boolean value. It just is dropped, python doesn’t act on it, and the next line is executed regardless.The second operation again splits the line to a list, selects the 9th element, and replaces that with the value of
residencetime. But, the result ofline.split()does not magically change the value oflist, it returns a list, which in this case doesn’t get assigned to anything and thus is dropped again.