2

I am looking for a way to extend a header of a CSV file. I have the file header in a dictionary (dict1) and another dictionary (dict2) with keys that some are duplicates of dict1 and would like to extend the header in the file.

I was told there is something like csv.header.extend() but not sure how it works and couldn't find examples.

My CSV looks like:

V,T1,T2,T3,T4 
U1,a,b,c,d
U2,q,w,e,r

Lets say dict2 is

dict2 = {'V': 'U3', 'T1': 'p', 'T2': 'o', 'T5': 'z'}

The CSV would come out like this:

V,T1,T2,T3,T4,T5
U1,a,b,c,d,
U2,q,w,e,r,
U3,p,o,,,z

Anyone knows how this would work?

1
  • Check out collections.defaultdict(str). Also check out dict1.update(dict2). HTH Commented Nov 13, 2013 at 22:14

1 Answer 1

1

I suggest using a csv.DictWriter which uses all fields:

fieldnames = ['V','T1','T2','T3','T4','T5']
with open(...) as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)

You can then write each row by passing a dictionary that contains the values of that row:

for my_dict in my_dicts:
    writer.writerow(my_dict)

So the steps to take are:

  • Compute a list that contains the headers of both files (i.e., merge ['V','T1','T2','T3','T4'] of the existing file with other headers that you may have, such as 'T5').
  • Compute dictionaries per row that contain a value for each of the headers. For example, your dict2 would need to become: dict2 = {'V': 'U3', 'T1': 'p', 'T2': 'o', 'T5': 'z', 'T3': '', 'T4': ''}.
  • After that you can use the above code to create the DictWriter with all the possible fields in the output file and you can write each of the output rows by passing them as dictionaries.
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.