2

I have two CSV files with the same row names:

Name, Lastname.

However, file2.csv has an extra column named

Attention

Each file has a different list of name and lastname (not in order). I'm trying to find a way to find to print the attention column, if the name and lastname are in both files.

This is what I have so far:

    with open('result.csv') as r:
        set1 = set(x[0] for x in csv.reader(r))

    with open('result2.csv') as r:
        set2 = set(x[0] for x in csv.reader(r))

    for x, y in zip(set1, set2):
        if x[0] == y[0]:
            print("Matched")

How can I read the first and second column for each file?

Thank you

edit: being more clear

3
  • How about using x[1]? Commented Jul 23, 2018 at 13:40
  • @Neo My bad, meant to say compare first and second column of each file. Commented Jul 23, 2018 at 13:41
  • It's not clear what is the comparison you want to make Commented Jul 23, 2018 at 13:42

1 Answer 1

2

Create a set of tuples for the lookup table which will contain the values from your first two columns, e.g.:

with open("result.csv", "r") as f:
    result = {(x[0], x[1]) for x in csv.reader(f)}

And then just iterate over the second file, check if the tuple of the first two columns exists in the lookup table from the first file, and if yes - print the third column on each match, e.g.:

with open("result2.csv", "r") as f:
    for row in csv.reader(f):
        if (row[0], row[1]) in result:
            print("Matched: {}".format(row[2]))  # print the third column
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.