filenames = 'file1.csv', 'file2.csv'
data = OrderedDict()
fieldnames = []
for filename in filenames:
    with open(filename, 'rb') as fp:
        reader = csv.DictReader(fp)
fieldnames.extend(reader.fieldnames)
for row in reader:
    data.setdefault(row['id'], {}).update(row)
fieldnames = list(OrderedDict.fromkeys(fieldnames))
with open('merged.csv', 'wb') as fp:
    writer = csv.writer(fp)
writer.writerow(fieldnames)
for row in data.values():
    writer.writerow([row.get(field, '') for field in fieldnames])
How do I merge two CSV files based on field and keep same number of attributes on each record?