Simon Kiely
Simon Kiely

Reputation: 6050

Match two columns in CSV; copy value from one CSV to other if equal

I have two CSVs which contain largely the same information; unfortunately one CSV is missing a number of values.

My first CSV is of the form :

url,urlid,boilerplate,label

The second is :

url, rank

I would like to copy the rank value from the first CSV into the second CSV on rows where the URL values are equal.

How can I accomplish this?

Upvotes: 1

Views: 1695

Answers (1)

fanti
fanti

Reputation: 1927

# create dict from first csv, with url as key
with open("first.csv", "r") as f:
    first = {rows[0]: rows[1:] for rows in list(csv.reader(f))}

# compare second csv and append rank
with open("second.csv", "r") as f:
    for row in csv.reader(f):
        if row[0] in first: # row[0] = url
            first[row[0]].append(row[1]) # row[1] = rank

# convert dict back to list
merged = [(k,) + tuple(v) for k, v in first.items()]

# write list to output csv
with open("output.csv", "w") as f:
    csv.writer(f).writerows(merged)

Upvotes: 3

Related Questions