cc211
cc211

Reputation: 397

Python: If Dictionary key matched in one column replace, another column with value

Simple question here, I have

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!

Upvotes: 0

Views: 480

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123700

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 the waternumber value is present in the dict with the in operator:

for line in otherinput:
    line = line.split()
    waternumber = int(line[1])
    if waternumber in twodee:
        line[9] = twodee[waternumber]
    print line

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:

            line.split()[1] == waternumber
            line.split()[9] = residencetime

The first operation splits the line to a list, selects the first elements and tests if that is equal to the waternumber value. This'll be either True or False, 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 of line.split() does not magically change the value of list, it returns a list, which in this case doesn't get assigned to anything and thus is dropped again.

Upvotes: 2

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40795

Some suggestions for you code:

  1. Don't use try-except when not specyfing more-or-less specific exception (specify only exceptions that you expect to happen). You have errors inside try-except and they are all silently passed.
  2. Your replacements won't help you as you don't store results in any meaningful way (you just change some iteration variable that is lost on each next iteration
  3. line.split()[1] == waternumber is not an assignment, it's a comparison, this line is evaluated as an expression and the result is lost further.
  4. The result of .split() is a brand new list object, whose item is changed; this new object is lost in further (see 2).

Upvotes: 2

Related Questions